2014-12-04 87 views
0

我試圖通過調用包含頁面控制器上的函數來設置指令屬性的值,但它不能按預期方式工作。在下面的代碼中,「make」對象沒有「modelList」屬性,所以我必須對服務器單獨調用以獲取每個make。通過調用函數設置角度指令屬性

<div ng-repeat="make in makeList"> 
    <model-list-directive model-list="getModelList(make)" /> 
</div> 

app.controller("myController",function($scope) { 
    $scope.getModelList = function(make) { 
    return null; 
    //return myService.getModelList(make); 
}; 
}) 

app.directive("modelListDirective",function() { 
    restrict:'E', 
    scope: { 
    modelList: '=' 
    }, 
    template: '<ul><li ng-repeat="model in modelList">{{model.modelName}}</li></ul>', 
    controller: ['$scope', function ($scope) { 
    }] 

如果getModelList()函數被設置爲返回null(未在代碼註釋),沒有給出錯誤,但是函數被調用多次(3和5之間隨機變化通常)。

真正的問題出現在我調用myService.getModelList(make)時(在代碼中註釋掉)。這導致對服務的調用無休止的循環,從而導致瀏覽器崩潰。

我猜這是因爲雙向綁定,但我不確定。

有沒有更好的方式來獲取動態數據的指令?

回答

1

我認爲部分問題是您的指令定義沒有返回對象。它應該是這樣的:

app.directive('modelListDirective',function() { 
    return { // <-- need to return an object 
     restrict:'E', 
     scope: { 
      modelList: '=' 
     },    
     template: '<ul><li ng-repeat="model in modelList">{{model.modelName}}</li></ul>', 
     controller: ['$scope', function ($scope) { 
     }] 
    }; 
}); 

但是,你傳遞函數爲2路結合成指令,這你不應該做。請參閱this對類似問題的回答。

您可以改爲直接將myService注入您的指令,然後讓您的指令myService.getModelList()在其link函數中調用。

所以您的標記應該是這樣的:

<div ng-repeat="make in makeList"> 
    <model-list-directive make="{{make}}" /> 
</div> 

每個指令實例將只需要make

而且你的指令的定義是這樣的:

app.directive('modelListDirective', ['myService', function(myService) { 
    return { 
     restrict:'E', 
     scope: { 
      make: '@' 
     }, 
     link: function (scope, element, attrs) { 
      scope.modelList = myService.getModelList(scope.make); 
     }, 
     template: '<ul><li ng-repeat="model in modelList">{{model.modelName}}</li></ul>', 
     controller: ['$scope', function ($scope) { 
     }] 
    }; 
}]); 

在其link功能設置scope.modelList

Here's a fiddle

+0

邁克,感謝您的輸入,特別是討論無限循環的鏈接。我會繼續編寫代碼將函數傳遞給指令,而不是所需的函數結果。對於那些發生在這個解決方案中的人,我的具體項目涉及一個以多種方式使用的指令,有時顯示與「make」相關聯的「模型」列表,有時顯示隨機的「模型」列表。處理第二個實例很容易,因爲該指令僅在頁面上使用一次。但是,第一個實例放置在中繼器中,需要動態生成模型列表。 – 2014-12-10 03:23:32