AngularJS rootScope constant
The Goal
Set value in html and use this value in Angular controller and directive.
Finally, we can insert value from server side, ex, ejs, thymeleaf, erb, etc…
Why is this important?
We sometimes set value in serverside, but, we want to manage data and draw data in angularjs. How to do this?
Example
index.html
<html> <head> <script src="bower_components/angular/angular.js"></script> <script src="js/app.js"></script> <script> app.constant('pv', { greeting: { morning: 'Good Morning', day: 'Hello' } }) .run(function($rootScope, pv) { $rootScope.$global = pv; }); </script> <script src="js/controller.js"></script> <script src="js/directive.js"></script> </head> <body ng-app="appModule" ng-controller="appController"> <div>{{greeting}}</div> <h3>Directive</h3> <first-div></first-div> </body> </html>
{{greeting}} is ‘Good Morning’
firstdiv shows ‘Hello’
app.js
var app = angular.module('appModule', []);
controller.js
app.controller('appController', function($scope, pv){ $scope.greeting = pv.greeting.morning; });
directive.js
app.directive('firstDiv', function($rootScope) { return { restrict: 'E', template: '<div>{{hello}}</div>', link: function($scope) { $scope.hello = $rootScope.$global.greeting.day; } }; });