2014-12-04 72 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