What is the best way to set a constant to use in views, services and controllers.
$rootScope or .constant()?
I tried .constant('CHAR_LIMIT', 10); but this cannot use in view {{CHAR_LIMIT}}
You can indeed add a constant to a module:
angular.module('app').constant('CHAR_LIMIT', 10);
and then have it injected using dependency injection anywhere Angular allows it:
angular.controller('someCtrl', ['CHAR_LIMIT', function(CHAR_LIMIT){
// Use the constant here
}]);
If you need it to be available in all your view templates, you can add it as a property to $rootScope in a run block:
angular.run(['$rootScope', 'CHAR_LIMIT', function($rootScope, CHAR_LIMIT){
$rootScope.CHAR_LIMIT = CHAR_LIMIT;
}]);
and then you can use it in your view templates like this:
{{CHAR_LIMIT}}
Notice: If you explicitly define a CHAR_LIMIT property in the child scope that is linked to the template, then that value will be used as it will 'override' the value set in the $rootScope.
Hope that helps!
You have to inject it in your controller like a service and then use it (like the following):
var myCtrl = ['$scope','CHAR_LIMIT', function($scope,CHAR_LIMIT){
$cope.myVar = CHAR_LIMIT;
}]
$scope. What if I assign it directly to $rootScope under run()?$parent.CHAR_LIMIT or in a more convenient way, inject $rootScope in your controller and then use $rootScope.CHAR_LIMIT. Bear in mind that you can only use in your markup, whatever variables you assign to that specific controller's $scope!