As we know like some short of configuration require in project level. How we do such configuration in Angularjs using Constant.
Let’s more talk about how to declare and use Constant configuration.
We are going to cover classic example of constant . Whenever you want to use config that could be ineluctable at any part of application and it works.
Lets see code here.
(function () { 'use strict'; angular .module('app', [ // Angular modules 'ngAnimate', 'ngRoute' // Custom modules // 3rd Party Modules ]) .constant('userRole', { owner: 'Owner', administrator: 'Administrator', user: 'User' }); })();
As define userRole as a constant in code same like JSON format so there are better way to config in your application. Classic way might be it is not best way to use constant instead of create a service and load with $http a JSON file.
Once you declare constant than how to use in your application.
(function () { 'use strict'; angular .module('app', [ // Angular modules 'ngAnimate', 'ngRoute' // Custom modules // 3rd Party Modules ]) .constant('userRole', { owner: 'Owner', administrator: 'Administrator', user: 'User' }) .controller('MainCtrl', function (userRole) { // Do something with myConfig... var vm = this; vm.Role = userRole.administrator; }); })();In the above code we have inject userRole on MainCtrl so we can use userRole inside the controller.
Define controller as vm (var vm = this) and userRole assign to Role property of controller like vm.Role = userRole.administrator;
You can find source code from GitHub.
That’s it. Hope you like it. Stay tuned for more!!
0 comments:
Post a Comment