1

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}}

2 Answers 2

3

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!

Sign up to request clarification or add additional context in comments.

1 Comment

Love the app.run idea instead of declaring it in a controller!
1

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;
}]

2 Comments

That means I still have to assign it to $scope. What if I assign it directly to $rootScope under run()?
Then you'll probably want to use it in this form: $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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.