如何使用复选框在angularjs中创建相关对象的数组列表

时间:2013-02-28 23:19:41

标签: angularjs

我有一个给定的对象数组,我想根据相关的复选框将其对象添加到“选定”列表中。如何在不必将控制器设置得太多的情况下进行设置。

当使用收音机时,这是小提琴,它很好用: http://jsfiddle.net/JohannesJo/6ru2R/

JavaScript的:

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

app.controller('controller', function($scope){
$scope.aData = [
    {i:1},
    {i:2}
];
$scope.aSelected = [];
});

HTML:

<body ng-app="app">
        <div ng-controller='controller'>
            <input type = "checkbox" ng-model = "aSelected"  value = "{{aData[0]}}">
            <input type = "checkbox" ng-model = "aSelected"  value = "{{aData[1]}}">

            <div>test:     {{oSelected}}</div>
         </div>
</body>

1 个答案:

答案 0 :(得分:2)

一个选项是监视oSelected数组上的更改,并根据它创建相关对象列表。

$scope.$watch(function () {
    return $scope.oSelected;
}, function (value) {
    $scope.selectedItems = [];
    angular.forEach($scope.oSelected, function (v, k) {
        v && $scope.selectedItems.push($scope.aData[k]);
    });
}, true);

jsfiddle http://jsfiddle.net/bmleite/zea7g/2/