【问题标题】:AngularJS - Checklist-Model doesn't update the model correctly on checkbox changeAngularJS - Checklist-Model 在复选框更改时未正确更新模型
【发布时间】:2018-12-06 05:22:05
【问题描述】:

我是 AngularJS 的新手,我遇到了 Checklist-Model 指令的问题。

我正在使用他们的一个示例来复制这种行为。 当我单击一个复选框并调用一个函数时,模型似乎已更新 正确并在模板上相应显示,但是当我在控制台上记录模型的内容时,我单击的复选框的值丢失了。 这是奇怪的事情开始的时候。如果我再次单击该复选框,则该值将从模板中删除,但我可以在控制台上看到它。

代码如下:

HTML:

<div ng-controller="DemoCtrl">
      <label ng-repeat="role in roles">
          <input type="checkbox" checklist-model="user.roles"
                 checklist-value="role.text"
                 ng-change="changeValues(role)"> {{role.text}}
      </label>
  <br>
  <button ng-click="checkAll()">check all</button>
  <button ng-click="uncheckAll()">uncheck all</button>
  <button ng-click="checkFirst()">check first</button>
  <br><br>
  user.roles {{ user.roles | json }}
</div>

角度:

angular.module("DemoApp", ["checklist-model"])
.controller('DemoCtrl', function($scope) {
$scope.roles = [
    {id: 1, text: 'guest'},
    {id: 2, text: 'user'},
    {id: 3, text: 'customer'},
    {id: 4, text: 'admin'}
  ];
  $scope.user = {
    roles: ['guest', 'admin']
  };
  $scope.checkAll = function() {
    $scope.user.roles = $scope.roles.map(function(item) { return item.id; });
  };
  $scope.uncheckAll = function() {
    $scope.user.roles = [];
  };
  $scope.checkFirst = function() {
    $scope.user.roles.splice(0, $scope.user.roles.length); 
    $scope.user.roles.push(1);
  };

    $scope.changeValues = function() {
    console.log('Roles: ', JSON.stringify($scope.user.roles));
  }
});

我第一次单击复选框时,即:“用户”,控制台上的输出是:

角色:["guest","admin"]

然后,当我取消选中同一个复选框时,输出是:

角色:["guest","admin","user"]

在我正在开发的应用程序中,当复选框更改其值时,我必须调用一个函数,这就是我使用“ng-change”指令的原因。

谁能解释我做错了什么? 提前致谢。

【问题讨论】:

标签: javascript angularjs checklist-model


【解决方案1】:

checklist-model 在复选框中使用 ID 作为 checklist-value,在您的代码中使用文本。 因此,在函数 $scope.checkAll 中,您应该返回 item.text 而不是 item.id 并在函数 $scope 中。 checkFirst 你应该推送 $scope.roles.find(item => item.id == 1).text 其余的似乎都是正确的

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-03
    • 1970-01-01
    • 1970-01-01
    • 2018-11-14
    • 2016-03-26
    • 2021-11-30
    • 1970-01-01
    相关资源
    最近更新 更多