javascript - 将动态值追加到数组 angularjs 中

标签 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"}]

最佳答案

每次点击时,$scope.dflt都会再次初始化...使其在 Controller 中全局化。

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>

关于javascript - 将动态值追加到数组 angularjs 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38184636/

相关文章:

javascript - 有什么方法可以检测用户何时突出显示或复制全部/部分 URL?

javascript - 如何使用 JS 更改网格模板列样式?

JavaScript 多个函数的回调

node.js - 咕噜连接代理重定向?

javascript - 处理同一页面中多种表单的 Angular ng-model

javascript - 删除对象属性在 Angular 中不起作用?

javascript - setTimeout(fun) 和 setTimeout(fun,4) 之间有区别吗

javascript - 使用 REST API 在 ExpressJS 和 AngularJS 中上传文件

javascript - 在 jQuery 中启用和禁用空格键

javascript - Chrome jQuery 表单插件跨域安全漏洞?