AngularJS:设置过滤的对象属性值在更改时不会自动更新

时间:2015-02-03 20:23:54

标签: javascript angularjs

我在范围上有一个数组,用于填充带有复选框的ng-repeat。

我在一个对象中有一个属性,我试图将其设置为包含已经过检查的ng-repeat中的复选框过滤的数组。

基本HTML:

<div ng-controller="MyCtrl">
    <ul>
        <li ng-repeat="box in boxes"><input type="checkbox" ng-model="box.checked" ng-click="testingOnly()"/> {{box.label}}</li>
    </ul>
    <div ng-repeat="object in objects.prop1">{{object.label}}</div>
    <div ng-repeat="object in objects.prop2">{{object.label}}</div>
</div>

基本JS:

function MyCtrl($scope, $filter) {
    $scope.boxes = [{label: 'Mon'}, {label: 'Tue'}, {label: 'Wed'}, {label: 'Thu'}, {label: 'Fri'}, {label: 'Sat'}, {label: 'Sun'}];

    $scope.objects = {
        prop1: [{label: 'You have chosen the following days:'}],
        prop2: $filter('filter')($scope.boxes, {checked: true})
    }

    $scope.testingOnly = function() {
     $scope.objects.prop2 = $filter('filter')($scope.boxes, {checked: true});
    }
}

JSFiddle:http://jsfiddle.net/97ton8ua/5/

我认为我不了解Angular如何运作的一些基本部分。我希望将两个部分连接在一起,并且 objects.prop2 将更新,而无需编写任何其他辅助函数。

是否有可能实现这一点(通过模型附件/标记/等中的某些内容......),或者每次单击复选框时都必须保持辅助函数运行?

1 个答案:

答案 0 :(得分:0)

为什么不按照这种方式进行操作并使用双向绑定,我认为更方便,更清晰:FIDDLE

<div ng-app="myApp">
<div ng-controller="MyCtrl">
    <ul>
        <li ng-repeat="box in boxes">
            <input type="checkbox" ng-model="selection.value" ng-true-value="{{box.label}}" ng-false-value="" />{{box.label}}</li>


    </ul>
        <div ng-repeat="object in objects.prop1">{{object.label}}</div>{{selection.value}}

</div>

</div>

angular.module('myApp', [])

.controller("MyCtrl", function($scope, $filter) {
    $scope.name = 'Superhero';
    $scope.boxes = [{
        label: 'something else'
    }, {
        label: 'world'
    }]; 
    $scope.selection = {};
    $scope.objects = {
        prop1: [{
            label: 'hello'
        }]
    };

});