将动态值附加到数组angularjs中

时间:2016-07-04 12:19:56

标签: javascript jquery angularjs

$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"}]

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

3 个答案:

答案 0 :(得分: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>

答案 1 :(得分:0)

false

答案 2 :(得分:0)

将$ scope.dflt设置在currrent函数之外,它会起作用。每次执行单击时,您都会覆盖数组以清空