2015-12-15 96 views
0

我有一個情況,有3個複選框(「最初選中」)。因爲它作爲3複選框,它將使用ng-repeat 3次並循環分割那裏的時間。現在,一旦我取消選中任何複選框,它應該顯示div 2次。到目前爲止,基於複選框獲取數組值

$scope.items = [ 
    {id: 0, title: "apple",selected:true}, 
    {id: 1, title: "orange",selected:true}, 
    {id: 2, title: "grapes",selected:true},  
]; 

在每個複選框中點擊ng,我稱之爲函數測試(「apple」)。我對着

$scope.test = function(vals) { 
    $scope.vl=[]; 
    for(var i=0;i<$scope.items.length;i++) { 
     if($scope.items[i].title == vals) { 
      console.log("dnt push"); 
     } 
     else { 
      $scope.vl.push({ 
       id: $scope.items[i].id, 
       title: $scope.items[i].title, 
       selected:true      
      }); 
     } 
    } 
    console.log("vl array"); 
    console.log($scope.vl); 
} 

問題是,它的工作原理罰款1日取消選中,但不是我多取消選中做。當我檢查未選中它不加載div。

在HTML中我使用像,

<div ng-repeat="item in vl"> some tags </div> 
+0

你是怎麼想precisly辦? – AlainIb

回答

2

不太清楚你的問題,但希望我的回答可以給你一些提示。

plunker demo

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

 
app.controller('MainCtrl', function($scope) { 
 
    $scope.name = 'World'; 
 

 
    $scope.items = [{ 
 
    id: 0, 
 
    title: "apple", 
 
    selected: true 
 
    }, { 
 
    id: 1, 
 
    title: "orange", 
 
    selected: true 
 
    }, { 
 
    id: 2, 
 
    title: "grapes", 
 
    selected: true 
 
    }]; 
 
});
<!DOCTYPE html> 
 
<html ng-app="plunker"> 
 

 
<head> 
 
    <meta charset="utf-8" /> 
 
    <title>AngularJS Plunker</title> 
 
    <script> 
 
    document.write('<base href="' + document.location + '" />'); 
 
    </script> 
 
    <link rel="stylesheet" href="style.css" /> 
 
    <script data-require="[email protected]" src="https://code.angularjs.org/1.4.8/angular.js" data-semver="1.4.8"></script> 
 
    <script src="app.js"></script> 
 
</head> 
 

 
<body ng-controller="MainCtrl"> 
 
    <p>Hello {{name}}!</p> 
 
    <div ng-repeat="item in items"> 
 
    <input type="checkbox" ng-model="item.selected">{{item.title}} 
 
    </div> 
 
    {{items | json}} 
 
</body> 
 

 
</html>

0

當且僅當你想把一個數組檢查誰的項目:

http://plnkr.co/edit/DvoPBBvKf3AhYM4qcBhx?p=preview

HTML

<div ng-repeat="item in items"> 
    <input type="checkbox" 
     ng-model="item.selected" ng-click="test(item.title)"> {{item.title}} 
</div> 

控制器

$scope.test = function(vals) { 
    $scope.vl=[]; 
    $scope.vlChecked=[]; 
    for(var i=0;i<$scope.items.length;i++) { 
    if($scope.items[i].selected) { 
     $scope.vlChecked.push({ 
     id: $scope.items[i].id, 
     title: $scope.items[i].title, 
     selected:true      
     }); 
    } 
    } 

    console.log("vlChecked array"); 
    console.log(JSON.stringify($scope.vlChecked)); 

}