AngularJS SilverStripe Integration

This post follows from my previous post (AngularJS 101) and discusses how to integrate AngularJS in a SilverStripe setting, which isn't too different from setting up AngularJS in stand-alone app setup but there are a few differences in setup that you'll need to make.  This article assumes that you're using Bower to manage your front end dependencies, if unsure refer to my earlier post (Bower Setup in SilverStripe).

Requirements

The following file structure is assumed within your template theme (/themes/yourtheme/):

bower_components/
-- templates/
----- CustomPage.ss
------- Layout
---------- CustomPage.ss -- javascript/ ----- app/ -------- app.js ----- main.js

Also, you will need to have installed the following Bower packages shown in bower.json below:

{
  "name": "app",
  "version": "1.0.0",
  "description": "App desc.",
  "license": "MIT",
  "ignore": [
    "**/.*",
    "node_modules",
    "bower_components",
    "test",
    "tests"
  ],
  "dependencies": {
    "angular": "~1.4.6"
  },
  "devDependencies": {
    "angular-resource": "~1.4.7",
    "angular": "~1.4.7"
  }
}

Steps

  1. Create Main (main.js) app that will be loaded
    require.config({
    	paths: {
    		app: 'app/app',
    		angular: '/themes/envmon/bower_components/angular/angular.min',
    		angularResource: '/themes/envmon/bower_components/angular-resource/angular-resource.min'
    	},
    	shim: {
    		app: {
    			deps: ['angular']
    		},
    		angular: {
    			exports: 'angular'
    		},	
    		angularResource: {
    			deps: ['angular']
    		}
    	}
    });
    require(['app'], function() {
    	angular.bootstrap(document, ['app']);
    });
    
  2. Create app.js
    define("app", ["angular", "angularResource"], function(angular) {
    	var app = angular.module("app", ["ngResource"] );
    	app.controller('MainController', function ($scope) {
    		$scope.employee = {};
    		$scope.employee.details = {
    			"name": "Zaid Al-Dabbagh",
    			"jobTitle": "Angular Developer"
    		};
    	return app;
    });
  3. Load app from within template
    <!DOCTYPE html>
    <html>
    <head>
    </head>
    <body data-ng-controller="MainController">
    	$Layout
    	<!-- Load Main with RequireJS -->
    	<script src="$ThemeDir/bower_components/requirejs/require.js" data-main="$ThemeDir/javascript/main.js"></script>
    </body>
    </html>
  4. Print out employee details in Layout template (CustomPage.ss)

    <h1>Test App</h1>
    <em>By {{ employee.details.name }} and {{ employee.details.jobTitle }}</em>
    

References
http://kielczewski.eu/2013/04/integrating-angularjs-with-requirejs/