这里是 Angular 菜鸟。
我正在尝试将我的工厂 (beerFactory) 注入(inject)到一个指令中,但我无法从我的链接函数中访问它。
正如您在我的代码中看到的,一旦我进入链接函数,我就会尝试通过控制台记录 beerFactory 对象。
工厂工作正常,因为我从另一个 Controller 内部使用它。
不知道我做错了什么
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
};
}]);
最佳答案
您还必须将其作为参数传递:
app.directive('starRating', ['beerFactory', function(beerFactory){
参见 https://docs.angularjs.org/guide/di -> 内联数组注释
When using this type of annotation, take care to keep the annotation array in sync with the parameters in the function declaration.
关于javascript - 工厂注入(inject)指令不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46786824/