2016-07-04 31 views
0
$scope.results = [ 
    {id: 1, text: 'a'}, 
    {id: 2, text: 'b'}, 
    {id: 3, text: 'c'}, 
    {id: 4, text: 'd'} 
]; 
<label ng-repeat="result in results"> 
    <input type="checkbox" name="res" data-checklist-model="my.resid" data-checklist-value="result.id" ng-click="myFunction(result.id)" > {{result.text}} 
</label> 
$scope.myFunction = function(id){ 
    $scope.dflt = []; 
    if($scope.my.resid == 1){ 
     $scope.dflt.push({"id": 1, "text": 'a'}); 
     console.log($scope.dflt); 
    } 
} 

我要动态地添加如我所料下面的结果,但现在它只是显示[{"id":1,"text":"a"}]追加动态重视到数组angularjs

[{"id":1,"text":"a"}, {"id":2,"text":"b"}, {"id":3,"text":"c"}, {"id":4,"text":"d"}] 
+0

在每一次点击,'$ scope.dflt'再次初始化时间......使它在全球控制器... – Rayon

回答

2

在每一次点击,$scope.dflt初始化再次......让它在控制器中成为全球。

var myApp = angular.module("myApp", []); 
 
myApp.controller("myCtrl", function($scope) { 
 
    $scope.results = [{ 
 
    id: 1, 
 
    text: 'a' 
 
    }, { 
 
    id: 2, 
 
    text: 'b' 
 
    }, { 
 
    id: 3, 
 
    text: 'c' 
 
    }, { 
 
    id: 4, 
 
    text: 'd' 
 
    }]; 
 
    $scope.dflt = []; 
 
    $scope.myFunction = function(obj) { 
 
    $scope.dflt.push(obj); 
 
    console.log($scope.dflt); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="myApp" ng-controller="myCtrl"> 
 
    <label ng-repeat="result in results"> 
 
    <input type="checkbox" name="res" data-checklist-model="my.resid" data-checklist-value="result.id" ng-click="myFunction(result)">{{result.id}} 
 
    </label> 
 
</div>

+0

这是硬编码,而不是动态地进行。 –

+0

@ItsikMauyhas,编辑正确吗? – Rayon

+1

是的,现在不是硬代码。投票。 –

0
$scope.results = [ 
    {id: 1, text: 'a'}, 
    {id: 2, text: 'b'}, 
    {id: 3, text: 'c'}, 
    {id: 4, text: 'd'} 
    ]; 


<label ng-repeat="result in results"> 
       <input type="checkbox" name="res" data-checklist-model="my.resid" data-checklist-value="result.id" ng-click="myFunction(result.id)" > {{result.text}} 
       </label> 


$scope.myFunction = function(id){ 

    $scope.dflt = $scope.dflt || []; 

      if($scope.my.resid == 1){ 
      $scope.dflt.push({"id": 1, "text": 'a'}); 
    console.log($scope.dflt); 
      } 

} 
+0

这是硬代码,并没有动态完成。 –

0

将$ scope.dflt的currrent功能之外,它会工作。要覆盖阵列清空每次执行一个点击