自定义过滤器让"无法读取不确定&QUOT财产'片';在AngularJS [英] Custom filter giving "Cannot read property 'slice' of undefined" in AngularJS
问题描述
我的自定义 startFrom
过滤器是给我一个错误。
app.filter('startFrom',函数(){
返回功能(输入,启动){
开始= +启动; //解析为int
返回input.slice(开始);
}
});app.controller(PostCtrl功能($范围,$ HTTP){
$ scope.currentPage = 0;
$ scope.pageSize = 10;
$ scope.hidePagination =真;$ scope.search =功能(){
$ http.get('someurl'),然后(sucesscalback,errorcalback)。
功能sucesscalback(响应)
{
$ scope.hidePagination = FALSE;
的console.log(成功);
的console.log(response.data.records);
$ scope.posts = response.data;
$ scope.numberOfPages = Math.ceil($ scope.posts.records.length / $ scope.pageSize);
警报($ scope.numberOfPages);
}
功能errorcalback(失败)
{
的console.log(错误:);
的console.log(失败);
}
您过滤器需要检查输入是否存在:
app.filter('startFrom',函数(){
返回功能(输入,启动){
如果(!输入|| input.length){返回; }
开始= +启动; //解析为int
返回input.slice(开始);
}
});
否则,过滤功能将运行,因此称之为片
在未定义
不具有的属性片
像数组或字符串一样。
虽然没有值过滤器被称为究其原因是因为当角运行其第一个 $消化
循环过滤器将运行。您可以通过在控制器中添加一个初始值,避免错误,但最好只到如果
语句添加到过滤器。
这里有两种解决方案的演示。注意没有错误。
My custom startFrom
filter is giving me an error.
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);
}
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 slice
on undefined
which doesn't have a property of slice
like an array or string does.
The reason the filter is called while there is no value is because the filter will run when Angular runs its first $digest
cycle. You could avoid the error by adding an initial value in the controller, but it's best just to add the if
statement to the filter.
Here's a demo of both solutions. Notice there are no errors.
这篇关于自定义过滤器让"无法读取不确定&QUOT财产'片';在AngularJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!