javascript AngularJS - 由于未定义的数组而导致自定义过滤器错误并且仍然正确过滤?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13364091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AngularJS - custom filter errors due to undefined arrays and still filters properly?
提问by Scott
I have an array of objects getting assigned to $scope
within a controller, and is being filtered in a series of divs within a partial template:
我$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>
The filters are displayed in a separate fieldset
element:
过滤器显示在单独的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>
I have a module set up with two filters, and pass that module on to my app:
我有一个设置了两个过滤器的模块,并将该模块传递给我的应用程序:
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;
}
});
I'm concerned that this code works, yet when looking at the error console, I get a bunch of errors saying Cannot read property 'length' of undefined
regarding the filterName
and entityType
filters' for loops. If I wrap those filter in an if statement to check if items
is defined (take for example filterName
):
我担心这段代码有效,但是在查看错误控制台时,我收到了一堆Cannot read property 'length' of undefined
关于filterName
和entityType
过滤器的 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;
}
});
It gets rid of the error and works as well. Why would AngularJS pass in undefined item
s to the filters? Where else could these filters be getting called if they are only explicitly getting called in my two ng-repeat
s?
它消除了错误并且也能正常工作。为什么 AngularJS 会将 undefined item
s传递给过滤器?如果仅在我的两个ng-repeat
s 中明确调用这些过滤器,还有哪些地方可以调用它们?
回答by dnc253
Is it safe to assume that the data going through your filters is retrieved from the server asynchronously? When the page first renders, and angular goes through everything, there is no data yet, so it is undefined. Once the data returns, it goes through the digest cycle again, and then there is data this time, so it all works. For this reason, it's a good idea to have the defined check at the beginning of the filter function.
假设从服务器异步检索通过过滤器的数据是否安全?当页面第一次渲染时,angular 遍历所有内容,还没有数据,所以它是未定义的。一旦数据返回,它再次经过digest循环,然后这次有数据,所以一切正常。出于这个原因,在过滤器函数的开头进行定义的检查是个好主意。
回答by saurabh seth
When the page renders, Angular examines everything. if in initial stage data is coming empty , then you should put check for undefined.
当页面呈现时,Angular 会检查所有内容。如果在初始阶段数据为空,那么您应该检查未定义。
app.filter('greaterThenHundred', function () {
return function (items) {
if (items == undefined)
items = [];
var filtered = [];
for (var i = 0; i < items.length; i++) {
var item = items[i];
if (item.Salary > 100) {
filtered.push(item);
}
}
return filtered;
};
});