2017-10-17 131 views
0

這裏的角度noob。工廠注入指令不起作用

我想注入我的工廠(beerFactory)到指令,但我無法從我的鏈接功能內訪問它。

正如你可以在我的代碼中看到的,我試圖控制檯登錄beerFactory對象,一旦我在鏈接函數中。

工廠工作正常,因爲我從另一個控制器內部使用它。

不知道什麼是我做錯了

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 
 
      }; 
 
}]);

回答

0

您也可以把它作爲參數:

app.directive('starRating', ['beerFactory', function(beerFactory){ 

https://docs.angularjs.org/guide/di - >在線陣註釋

使用這種類型的註釋時,注意保持註釋數組與參數在函數聲明中保持同步。

+0

謝謝你,它工作 –