Angular has a compile process. Functions might not be ready when directives need them. Constants are compiled and evaluated earlier than directives. The constants defined in mySettings is ready for use by directives when called.
Using constants also helps keep some order in the app. I'm using the same names or interface for the constants on each page. Some constants such as apiUri are referenced five or six times on each page. Each page has different values, but the interface is the same. I prefer constants over hard coding strings.
The directive shown below is not my service, don't let the name fool you. I use it to call an xml file. Then directives with lower priorities generate behavioral aspects for the page. My app is more document centric than model centric. The MVC is very light.
//root module
var myApp = angular.module('CoiApp',[]);
//constants
myApp.constant('mySettings', {
apiUri: '/api/foo',
nsUri: 'mySite/foo.xsd',
nsPrefix: 's'
});
//directive using constants, mySettings is injected in using the minification safe method.
mayApp.directive('getById',
['$log', '$location', 'mySettings'
function ($log, $location, mySettings) {
return {
priority: 500,
templateUrl: mySettings.apiUri +'/' + ($location.search()).myid
};
}]);
Awesome primer. We are using this pretty extensively as part of our open web stack. Fun!
ReplyDeleteCan you send me a url, I'd love to check it out.
Deletehttps://github.com/OpenWebStack
DeleteThank you Dear! It was really useful.
ReplyDeleteThanks. At least if this was fucking documented properly.
ReplyDeleteThanks Eric!
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteThanks for this little nugget that helped me very much.
ReplyDeleteHow can i access the constant in template.html
ReplyDeletesure,
Delete[...].controller('myController', ['$scope', 'mySettings' function ($scope, mySettings) {
$scope.mySettings = mySettings;
})
then in your template you can just use {{mySettings.priority}}
It might helpful for "How to create and inject the constants in AngularJs?"
ReplyDeletehttp://www.code-sample.com/2015/06/angularjs-constants.html
This concept is a good way to enhance the knowledge.thanks for sharing..
ReplyDeleteAngular JS Training in Hyderabad
Angular JS Training in Ameerpet
Angular JS Training
Angular JS Online Training
most useful topic
ReplyDeleteFull Stack Training in Chennai | Certification | Online Training Course | Full Stack Training in Bangalore | Certification | Online Training Course | Full Stack Training in Hyderabad | Certification | Online Training Course | Full Stack Training in Pune | Certification | Online Training Course | Full Stack Training | Certification | Full Stack Online Training Course