2016-04-06 60 views
0

我有一個數組如下更新陣列,以在angularjs選中的複選框的值

var selected = []; 

$scope.listA = [ 
    { 
    name : "Sample 1" 
    }, 
    { 
    name : "Sample 2" 
    }, 
    { 
    name : "Sample 3" 
    } 
]; 

輸入html元素是

<div ng-repeat="label in checkMode()"> 
    <input type="checkbox" checked> {{ label.name }}</input> 
</div> 

我怎樣才能基於該複選框選擇的值的陣列檢查? 例如,我想獲得下列選定的值

var selected = ["sample 1","sample 3"]; 

還能夠更新數組。

+0

可以幫助你http://stackoverflow.com/questions/36244427/angular-js-inputradio-doesnt-work/36244545#36244545 –

+0

' {{label.name}}' – Rayon

回答

0

它很容易..

在複選框添加點擊功能,希望這應該工作...參考鏈接... jsbin

<div ng-repeat="label in checkMode()"> 
    <input type="checkbox" checked ng-click="toggleSelection(label.name)> {{ label.name }}</input> 
</div> 
$scope.listA = { 
    name : "Sample 1" 
    }, 
    { 
    name : "Sample 2" 
    }, 
    { 
    name : "Sample 3" 
    } 
]; 

$scope.selected=[]; 

    $scope.toggleSelection = function toggleSelection(selected) { 
    var idx = $scope.selected.indexOf(selected); 

    // is currently selected 
    if (idx > -1) { 
     $scope.selected.splice(idx, 1); 
    } 

    // is newly selected 
    else { 
     $scope.selected.push(fruitName); 
    } 
    }; 
+0

你能分享一個小提琴嗎? –

+0

https://jsbin.com/kayivacife/1/edit?html,js,output – nisar

0

您可以使用ng-checked實現這個像

var app = angular.module('my-app', [], function() {}) 
 

 
app.controller('AppController', function($scope) { 
 
    $scope.selected = ['Sample 2']; 
 

 
    $scope.listA = [{ 
 
    name: "Sample 1" 
 
    }, { 
 
    name: "Sample 2" 
 
    }, { 
 
    name: "Sample 3" 
 
    }]; 
 

 
    $scope.toggleChecked = function(item) { 
 
    var index = $scope.selected.indexOf(item.name); 
 
    if (index == -1) { 
 
     $scope.selected.push(item.name); 
 
    } else { 
 
     $scope.selected.splice(index, 1); 
 
    } 
 
    } 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="my-app"> 
 
    <div ng-controller="AppController"> 
 
    <div ng-repeat="label in listA"> 
 
     <input type="checkbox" ng-checked="selected.indexOf(label.name) > -1" ng-click="toggleChecked(label)">{{ label.name }} 
 
    </div> 
 
    <pre>{{selected}}</pre> 
 
    </div> 
 
</div>