【问题标题】:Cannot read property 'toLowerCase' of undefined angularjs无法读取未定义 angularjs 的属性“toLowerCase”
【发布时间】:2016-08-04 03:32:34
【问题描述】:

我正在尝试在我的 angularjs“webapp”中创建搜索功能。当我在产品中搜索时一切正常,但是当我更改所有内容以便搜索用户时,我收到错误无法读取未定义的属性“toLowerCase”。

这是我的 js:

    return function(arr, searchString){
    if(!searchString){
        return arr;
    }
    var result = [];
    searchString = searchString.toLowerCase();
    angular.forEach(arr, function(item){
        if(item.title.toLowerCase().indexOf(searchString) !== -1){
            result.push(item);
        }
    });
    return result;
};
});

这是调用它的 html:

<div ng-controller="userCtrl" class="container-app">
<div class="bar">
    <input type="text" class="search" ng-model="searchString" placeholder="Enter your search terms" />
</div>
<div class="searchResultsText">
    <h2>Zoekresultaten: </h2>
</div>
<div class="searchResults" ng-repeat="user in users | searchFor:searchString">
    <a class="normal" href="#">{{user.name}}</a>
</div>

它确实向我显示了用户列表,就在我开始在搜索栏中输入时,它给了我错误。

当我使用完全相同的功能,使用不同的控制器时,它可以工作。这是 2 个控制器:

app.controller('customersCtrl', function ($scope, $http) {
$http.get(apiUrl + "product/list")
    .success(function (response) {
        $scope.products = response;
    });
});

app.controller('userCtrl', function ($scope, $http) {
$http.get(apiUrl + "user/list")
    .success(function (response) {
        $scope.users = response;
    });
});

所以基本上 customerCtrl 工作正常,但是当我将值更改为 userCtrl 时它停止工作。

有什么建议吗?

【问题讨论】:

  • 您的 searchString 可能为空
  • 怎么可能是空的?这是完全相同的功能...

标签: html angularjs


【解决方案1】:

item.title 很可能至少有一次未定义。

return function(arr, searchString){
    if(!searchString){
        return arr;
    }
    var result = [];
    searchString = searchString.toLowerCase();
    angular.forEach(arr, function(item){
        if(
            angular.isDefined(item.title) && 
            item.title.toLowerCase().indexOf(searchString) !== -1
        ){
            result.push(item);
        }
    });
    return result;
};

【讨论】:

  • 这修复了错误,但它不会返回结果
  • 啊,在这种情况下,将console.log(item); 放入循环中以检查返回的内容,因为该项目没有标题属性。 :)
  • 你是个男人,我应该大声读出每一行代码......谢谢它有效。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-28
  • 2020-07-23
  • 2020-06-24
  • 2018-10-23
  • 2021-05-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多