如果您有一个包含ng-repeat的指令,并且您想要修改ng-repeat的模型,那么如何在模板中不创建两个单独的ng-repeats的情况下这样做?我希望能够将ng-repeat的模型作为指令属性传递。所以在字符串数组的情况下,它就像repeat-model =" row"在对象数组的情况下,它将是repeat-model =" row.title"。有没有办法实现这个目标?
angular.module("app", []);
angular.module("app")
.controller("appCtrl", function($scope) {
$scope.sampleData = ["sample 1", "sample 2", "sample 3"];
$scope.sampleData2 = [{title:"sample 1"}, {title:"sample 2"}, {title:"sample 3"}];
})
angular.module("app")
.directive("repeatDirective", function() {
return {
restrict: 'E',
scope: {
data: '='
},
template: "<div ng-repeat='row in data'>{{row}}</div>",
link: function (scope) {}
}
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app">
<div ng-controller="appCtrl">
<repeat-directive data="sampleData"></repeat-directive>
</div>
</body>
&#13;
答案 0 :(得分:2)
您可以将另一个属性传递给您的指令,描述您要检查的属性。我在我使用的指令中做了类似的事情:
<repeat-directive data="sampleData2" property="title"></repeat-directive>
<repeat-directive data="sampleData"></repeat-directive>
然后在你的指令中:
.directive("repeatDirective", function() {
return {
restrict: 'E',
scope: {
data: '=',
property: '@?'
},
template: "<div ng-repeat='row in data'>{{row | repeatDirectiveDisplay:property:useProperty}}</div>",
link: function (scope) {
scope.useProperty = !angular.isUndefined(scope.property) && scope.property != null;
}
}
})
然后你有一个名为repeatDirectiveDisplay
的新过滤器,如:
app.filter('repeatDirectiveDisplay', function() {
return function(item, property, useProperty) {
if (useProperty)
return item[property];
return item;
}
});