vulpix vulpix - 19 days ago 6
AngularJS Question

How to reference a value inside of an Angular directive's link function?

I have defined a

value
called
myValue
for my Angular app. I would like to access
myValue
from the
link
method of a directive I have, but I haven't been able to make this work. Here is my code:

angular.module('extApp').value('myValue', {
foo: null,
bar: null
});

angular.module('extApp')
.directive('myDirective', ['constants', 'myValue', function(constants, myValue) {
return {
restrict: 'E',
template: '<div></div>',
scope: {
location: '=',
connectionType: '='
},
controller: function($scope) {
...
},
link: function(scope, element, attr) {
scope.myFunction = function() {
// Want to be able to reference my myValue here! For example:
if (myValue.foo != null && myValue.foo > 0) {
// myValue.foo doesn't work because it sees myValue as undefined
}
}

scope.myOtherFunction = function() {
...
}

scope.myFunction();
}
}
}]);


Do you have any suggestions?

Thank you in advance.

Answer

Just use it inside the function:

  scope.myFunction = function() {
    console.log(myValue);
  }

It will be injected using angularjs DI into directive function and accessible inside myFunction through closure.