我$scope
在控制器中分配了一组对象,并在部分模板中的一系列 div 中进行过滤:
<div class="entity-list">
<!-- Folders -->
<div class="entity-listing folder" ng-repeat="child in folders | filterName:nameFilter | entityType:filterType | orderBy:orderProp:orderAscDesc">
<!-- Some HTML -->
</div>
<!-- Files -->
<div class="entity-listing document" ng-repeat="child in documents | filterName:nameFilter | entityType:filterType | orderBy:orderProp:orderAscDesc">
<!-- Some HTML -->
</div>
</div>
过滤器显示在一个单独的fieldset
元素中:
<fieldset id="filters">
<legend>Filters</legend>
<label for="filter-name">Name Contains:</label>
<input id="filter-name" ng-model="nameFilter">
<label for="filter-type">Show:</label>
<select id="filter-type" ng-model="filterType">
<!-- some options -->
</select>
<label for="sort-field">Sort By:</label>
<select id="sort-field" ng-model="orderProp">
<!-- some options -->
</select>
<select ng-model="orderAscDesc">
<!-- some options -->
</select>
</fieldset>
我有一个设置了两个过滤器的模块,并将该模块传递给我的应用程序:
angular.module('widget', ['filters']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/homefolder', {templateUrl: 'widget/partial/entity-list.html', controller: HomeFolderCtrl}).
when('/folder/:uuid', {templateUrl: 'widget/partial/entity-list.html', controller: FolderCtrl}).
otherwise({redirectTo: '/homefolder'});
}]);
angular.module('filters', []).
filter('entityType', function() {
return function(items, type) {
var returnArray = [];
for (var i=0,ii=items.length;i<ii;i++) {
if (type == "both") {
returnArray.push(items[i]);
} else if (items[i].type == type) {
returnArray.push(items[i]);
}
}
return returnArray;
}
}).
filter('filterName', function() {
return function(items, str) {
var returnArray = [];
if (str != '') {
for (var i=0,ii=items.length;i<ii;i++) {
if (items[i].name.indexOf(str) !== -1) {
returnArray.push(items[i]);
}
}
} else {
returnArray = items;
}
return returnArray;
}
});
我担心这段代码可以工作,但是在查看错误控制台时,我收到一堆Cannot read property 'length' of undefined
关于filterName
andentityType
过滤器 for 循环的错误。如果我将这些过滤器包装在 if 语句中以检查是否items
已定义(例如filterName
):
filter('filterName', function() {
return function(items, str) {
var returnArray = [];
if (items) {
if (str != '') {
for (var i=0,ii=items.length;i<ii;i++) {
if (items[i].name.indexOf(str) !== -1) {
returnArray.push(items[i]);
}
}
} else {
returnArray = items;
}
}
return returnArray;
}
});
它消除了错误并且也可以正常工作。为什么 AngularJS 会将 undefined 传递item
给过滤器?如果这些过滤器只在我的两个ng-repeat
s中被显式调用,它们还能在哪里被调用?