Module scope example
http://angularjs.org/
by John Harley
HTML
<script src="http://code.angularjs.org/1.2.0/angular.min.js"></script>
<div ng-controller="GetNameCtrl">1. Hello, {{name}}!</div>
<div ng-app="myApp">
<div ng-controller="SetFredCtrl">2. Remember {{name}}</div>
</div>
<div ng-controller="GetNameCtrl">3. Hello, {{name}}!</div>
<div ng-app="myApp2"> <!-- second ngapp call does nothing -->
<div ng-controller="MyLastCtrl">4. Goodbye, {{name}}!</div>
<div id="myApp2"> <!-- called by document.ready bootstrap -->
<div ng-controller="SetBobCtrlApp2">5. Remember {{name}}</div>
<div ng-controller="GetNameCtrl">6. Hello, {{name}}!</div>
<div ng-controller="MyLastCtrl">7. Goodbye, {{name}}!</div>
</div>
<div ng-controller="GetNameCtrl">8. Hello, {{name}}!</div>
<div ng-controller="MyLastCtrl">9. Goodbye, {{name}}!</div>
</div>
<div id="myApp3"> <!-- called by document.ready bootstrap -->
<div ng-controller="GetNameCtrl">1. Outer, {{name}}!</div>
<div id="myApp4"> <!-- called by document.ready bootstrap -->
<div ng-controller="GetNameCtrl">2. Inner App2, {{name}}!</div>
</div>
<div ng-controller="GetNameCtrl">3. Outer, {{name}}!</div>
</div>
<div id="myApp5"> <!-- called by document.ready bootstrap -->
<div ng-controller="GetNameCtrl">4. Try App2 again, {{name}}!</div>
</div>
JavaScript
var myApp = angular.module('myApp', [])
.factory('UserService', function () {
return {
name: 'anonymous'
};
})
.controller('SetFredCtrl', ['$scope', 'UserService', function ($scope, UserService) {
UserService.name = 'fred';
$scope.name = UserService.name;
console.log("log: executed SetFredCtrl");
}]);
function GetNameCtrl($scope, UserService) {
$scope.name = UserService.name;
}
var myApp2 = angular.module('myApp2', [])
.factory('UserService', function () {
return {
name: 'epinonymous'
};
})
.controller('SetBobCtrlApp2', ['$scope', 'UserService', function ($scope, UserService) {
UserService.name = 'bob';
$scope.name = UserService.name;
console.log("log: executed SetBobCtrlApp2");
}])
.factory('LastService', function () {
return {
name: 'endomous'
};
});
function MyLastCtrl($scope, LastService) {
$scope.name = LastService.name;
}
angular.element(document).ready(function () {
angular.bootstrap(document.getElementById('myApp2'), ['myApp2']);
angular.bootstrap(document.getElementById('myApp3'), ['myApp']);
angular.bootstrap(document.getElementById('myApp4'), ['myApp2']);
angular.bootstrap(document.getElementById('myApp5'), ['myApp2']);
});