我试图设置一个指令,这样我就可以传入要在指令中使用的数据,以及将在其中使用ng-repeat的特定过滤器。这不起作用,所以我认为我对整个问题的处理是错误的。
如何传入过滤器?或者,我如何预先过滤/排序我传入的列表?
(范围必须隔离,因为我希望在同一页面上有多个列表。)
<!DOCTYPE HTML>
<html ng-app="MyApp">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<script>
var myApp = angular.module('MyApp', []);
myApp.controller('mainPage',function($scope){
$scope.cars = ["Saab","Volvo","BMW"];
});
myApp.directive('carList',function(){
return {
scope: {
listOfCars: '=',
carFilter : '@'
},
restrict: 'E',
replace: 'true',
template: '<table>\
<tr ng-repeat="{{carFilter}}">\
<td>{{car}}</td>\
</tr>\
</table>'
};
});
</script>
</head>
<body ng-controller="mainPage">
<car-list list-of-cars="cars" car-filter='car in listOfCars | orderBy:"toString()"' ></car-list>
</body>
</html>
带有上述代码的Plunker: http://plnkr.co/edit/ipsF15?p=preview
答案 0 :(得分:0)
好的,所以我认为这是一个可行的解决方案 - 而不是传入过滤器,传递过滤后的列表,如下所示:
<!DOCTYPE HTML>
<html ng-app="MyApp">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="angular.min.js"></script>
<script>
var myApp = angular.module('MyApp', []);
myApp.controller('mainPage',function($scope){
$scope.cars = ["Saab","Volvo","BMW"];
});
myApp.directive('carList',function(){
return {
scope: {
listOfCars: '&',
},
restrict: 'E',
replace: 'true',
template: '<table>\
<tr ng-repeat="car in listOfCars()">\
<td>{{car}}</td>\
</tr>\
</table>'
};
});
</script>
</head>
<body ng-controller="mainPage">
<car-list list-of-cars="cars | orderBy:'toString()' | limitTo:2 " ></car-list>
</body>
</html>
哪种感觉不太直观。这是正确的做法吗?