6

I am handling many variable in my application, I dont want to define the string each and every time. Instead of that I want to access the string from one file and access through all the files in my application.

Eg:

one = 1;

I want to access 1 with the variable name one in my application, because in future it can be changed as one (one = one) that time I cant change in all the place.

In order to avoid such difficulty am going for the constant file.

0

2 Answers 2

4

You can create a service and access it in any controller by injecting it.

angular.module('app')
.constant('CONSTANTS', {something: 12});

your controller

angular.module('app').controller('mainCtrl', function (CONSTANTS) {              
    $scope.mainctrlvariable = CONSTANTS.something;
});

your another controller

angular.module('app').controller('otherCtrl', function (CONSTANTS) {              
        $scope.otherCtrlvariable = CONSTANTS.something;
    });
Sign up to request clarification or add additional context in comments.

3 Comments

If am going to user more and more constant mean I can use like this {something: 12},{one: 1} of {something: 12, one:1}. In which way I have to use
yes, you can add more and more constants to the hash.... {something: 12, one:1, more: 20, two: 13}.
okay I will check with it and if its works well I will up you.
1

Angular provides constants and values services, that may help you

'use strict';
angular
    .module('App', [])
    .constant("config", {
        one:1,
        two:2
    })
    .config(function () { })
    .controller('MainCtrl', function (config) {
        console.log(config.one)
    });

Comments

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.