动态追加值到数组angularjs

append dynamically value into array angularjs

本文关键字:数组 angularjs 追加 动态      更新时间:2023-09-26
$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"}]

每次点击,$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>

$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);
          }
}

Make $scope。在当前函数之外的DFLT,它会工作。每次执行单击

时,都将数组重写为空。