Ludmila Ludmila - 14 days ago 8
Javascript Question

Can't get access to Angular constant

I'm trying to get access to my angular

.constant
via this code:

angular
.module('coreApp')
.constant('MY_CONSTANTS', {
myConstant_1: 'My constant'
})


My controller:

.controller('MyController', ['$log', '$rootScope', '$location', MY_CONSTANTS, MyController]);

function MyController($log, $rootScope, $location, MY_CONSTANTS, MyController) {
$log.debug(myConstant_1);
}


But i can't get the value and output the value from my constants. What's wrong with my code?

Answer

You have to wrap dependency inside single quote/double quote while specifying it inside an array. Here you are missing quotes aroud MY_CONSTANTS.

And then at the end of DI Array, it should be your controller function ArticleController not MyController

.controller('MyController', 
   ['$log', '$rootScope', '$location', 'MY_CONSTANTS', ArticleController]);
                                      //^^^^^ change here..
function ArticleController($log, $rootScope, $location, MY_CONSTANTS) {
    $log.debug(MY_CONSTANTS.myConstant_1);
}
Comments