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

AngularJS: Setting filtered object property value doesn't update automatically on change

本文关键字:更新 过滤 设置 对象 属性 AngularJS      更新时间:2023-09-26

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

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

基本网页:

<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 将在不编写任何其他帮助程序函数的情况下更新。

是否可以完成此操作(通过模型附件/标记中的某些内容/等...),或者我是否必须保持每次单击复选框时都运行帮助程序函数?

你为什么不这样做并使用双向绑定,我认为更容易和更干净: 小提琴

<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'
        }]
    };
});
相关文章: