Reputation: 13
Angular noob here.
I'm trying inject my factory(beerFactory) into a directive, but i'm unable to access it from within my link function.
As you can see in my code, i'm trying to console log the beerFactory object once i'm inside the link function.
The factory is working properly, since i'm using it from inside another controller.
No idea what's i'm doing wrong
app.directive('starRating', ['beerFactory', function(){
return {
restrict: 'EA',
scope: {
'value': '=value',
'max': '=max',
'hover': '=hover',
'isReadonly': '=isReadonly'
},
link: function(scope, element, attrs, ctrl) {
console.log(beerFactory);
function renderValue() {
scope.renderAry = [];
for (var i = 0; i < scope.max; i++) {
if (i < scope.value) {
scope.renderAry.push({
'fa fa-star fa-2x': true
});
} else {
scope.renderAry.push({
'fa fa-star-o fa-2x': true
});
}
}
}
scope.setValue = function (index) {
if (!scope.isReadonly && scope.isReadonly !== undefined) {
scope.value = index + 1;
}
};
scope.changeValue = function (index) {
if (scope.hover) {
scope.setValue(index);
} else {
// !scope.changeOnhover && scope.changeOnhover != undefined
}
};
scope.$watch('value', function (newValue, oldValue) {
if (newValue) {
scope.updateRating(newValue);
renderValue();
}
});
scope.$watch('max', function (newValue, oldValue) {
if (newValue) {
renderValue();
}
});
},
template: '<span ng-class="{isReadonly: isReadonly}">' +
'<i ng-class="renderObj" ' +
'ng-repeat="renderObj in renderAry" ' +
'ng-click="setValue($index)" ' +
'ng-mouseenter="changeValue($index, changeOnHover )" >' +
'</i>' +
'</span>',
replace: true
};
}]);
Upvotes: 1
Views: 53
Reputation: 6579
You also have to pass it as argument:
app.directive('starRating', ['beerFactory', function(beerFactory){
See https://docs.angularjs.org/guide/di -> Inline Array Annotation
When using this type of annotation, take care to keep the annotation array in sync with the parameters in the function declaration.
Upvotes: 1