Javascript 自定义过滤器在 AngularJS 中给出“无法读取未定义的属性‘切片’”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25723455/
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
Custom filter giving "Cannot read property 'slice' of undefined" in AngularJS
提问by Fahad Khan
My custom startFromfilter is giving me an error.
我的自定义startFrom过滤器给了我一个错误。
app.filter('startFrom', function() {
return function(input, start) {
start = +start; //parse to int
return input.slice(start);
}
});
app.controller("PostCtrl", function($scope, $http) {
$scope.currentPage = 0;
$scope.pageSize = 10;
$scope.hidePagination = true;
$scope.search = function() {
$http.get('someurl').then(sucesscalback,errorcalback);
function sucesscalback(response)
{
$scope.hidePagination = false;
console.log("Success:");
console.log(response.data.records);
$scope.posts = response.data;
$scope.numberOfPages=Math.ceil($scope.posts.records.length/$scope.pageSize);
alert($scope.numberOfPages);
}
function errorcalback(failure)
{
console.log("Error:");
console.log(failure);
}
回答by m59
Your filter needs to check whether or not the input exists:
您的过滤器需要检查输入是否存在:
app.filter('startFrom', function() {
return function(input, start) {
if (!input || !input.length) { return; }
start = +start; //parse to int
return input.slice(start);
}
});
Otherwise, the filter function will run and thus call sliceon undefinedwhich doesn't have a property of slicelike an array or string does.
否则,该滤波器函数将运行,从而调用slice上undefined不具有的特性slice等的数组或字符串一样。
The reason the filter is called while there is no value is because the filter will run when Angular runs its first $digestcycle. You could avoid the error by adding an initial value in the controller, but it's best just to add the ifstatement to the filter.
在没有值时调用过滤器的原因是过滤器将在 Angular 运行其第一个$digest周期时运行。您可以通过在控制器中添加初始值来避免该错误,但最好只是将if语句添加到过滤器中。
Here's a demo of both solutions.Notice there are no errors.
这是两种解决方案的演示。注意没有错误。

