【问题标题】:Filters not working on array from resource过滤器不适用于资源中的数组
【发布时间】:2015-05-08 12:57:48
【问题描述】:

我有一个过滤器,它在工厂的阵列上运行时不返回任何内容。但是当我将数组直接复制粘贴到过滤器中时,它工作正常。一定有一个简单的解决方案,这让我发疯了。

这行得通:

$filter('filter')([
  {"name":"firstItem","code":"one"},
  {"name":"secondItem","code":"two"},
  {"name":"thirdItem","code":"three"}
],"two",true);

这不是:

$filter('filter')($scope.items,"two",true);

角度示例:

angular.module('App', ['ngResource'])

.controller('Ctrl', function($scope, $filter, Items) {
  $scope.items = Items.query();
  var codeToFilter = "two";
  $scope.badFilter = $filter('filter')($scope.items,codeToFilter,true);
  $scope.goodFilter = $filter('filter')([
    {"name":"firstItem","code":"one"},
    {"name":"secondItem","code":"two"},
    {"name":"thirdItem","code":"three"}
  ],"two",true);
})

.factory("Items", function ($resource) {
    return $resource("item-list.asp");
});

以及从item-list.asp返回的数组:

[{"name":"firstItem","code":"one"},{"name":"secondItem","code":"two"},{"name":"thirdItem","code":"three"}]

这是我在页面上看到的:

Bad Filter: []
Good Filter: [{"name":"secondItem","code":"two"}]

【问题讨论】:

    标签: arrays angularjs angularjs-filter angularjs-resource


    【解决方案1】:

    Items.query() 是异步的,因此不会立即解决。在您的过滤器被点击时,它没有被填充。

    这样设置:

    Items.query(function(result) {
        $scope.items = result;
        $scope.badFilter = $filter('filter')($scope.items,codeToFilter,true);
    });
    

    【讨论】:

    • 感谢您的回复!现在我在Items.query 线上收到TypeError: undefined is not a function
    【解决方案2】:

    试试这个,它将在数组中添加到控件中,以帮助将信息传递给函数。

    .controller('Ctrl', ['$scope', '$filter', 'Items', function($scope, $filter, Items) {
    

    然后不要忘记在函数关闭花括号后关闭方括号

    【讨论】:

    • 这正是他正在做的,只是你让它缩小安全:)
    • 我一直想知道我们为什么要这样做!我只知道这通常是我的问题所在。仍在学习 Angular,很高兴您的回答对您有所帮助。
    猜你喜欢
    • 2014-12-24
    • 2019-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多