AngularJS - 自定义过滤器,模型不会在视图中更新

时间:2014-04-11 20:50:07

标签: angularjs angularjs-directive angularjs-scope angular-filters

我有一个自定义过滤器设置,当用户点击复选框时会触发。我使用一个指令来呈现DOM元素,并在复选框上附加一个监听器,当单击该复选框时,会触发filter上公开的$scope函数。

视图中使用的$scope.model应该被过滤函数的结果覆盖,并且返回对象看起来没问题(例如console.log())但视图不会更新。我做错了什么?

http://jsfiddle.net/r3pXc/1/

视图

<body ng-app="app">

<div ng-controller="mainCtrl">
    <div list-directive />
</div>

模板:

<script type="text/ng-template" id="list.html">
   <input type="checkbox" class="control">

   <div ng-repeat="player in model">
      Name: {{player.firstName}}, Price: {{player.price}}
   </div>
</script>

模块和控制器:

var app = angular.module('app', []);

app.controller('mainCtrl', ['$scope', '$filter', function($scope, $filter){
    $scope.model = [{ firstName: 'foo', price: 100 }, { firstName: 'bar', price: 50 }, { firstName: 'foobar', price: 0}];

    $scope.filter = function() {
        $scope.model = $filter('listFilter')($scope.model);
        console.log($scope.model);
    }
}]);

指令:

app.directive('listDirective', function(){
    return {
        restrict: 'AE',
        templateUrl: 'list.html',
        link: function($scope, iElm, iAttrs, controller) {
            iElm.bind('click', function(e){
                var el = angular.element(e.target);

                if (el.hasClass('control')) {
                    $scope.filter();
                };
            });
        }
    };
});

过滤器:

app.filter('listFilter', function(){
    return function(input) {
        var results = [];

        angular.forEach(input, function(val, key){
            if (val.price != 0) {
                results.push(val);
            }
        });

        return results;
    }
});

1 个答案:

答案 0 :(得分:0)

需要使用$apply()手动调用摘要周期,因为我不会使用ng-事件处理程序来监听元素:

$scope.filter = function() {
    $scope.model = $filter('listFilter')($scope.model);
    $scope.$apply();
}