2016-07-04 3 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"}]Append динамически значение в массиве 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

Make $ scope.dflt вне currrent функции и она будет работать. Вы переписываете массив пустым каждый раз, когда вы выполняете щелчок

Смежные вопросы