AngularJS-Checklist-Model在复选框更改时无法正确更新模型

时间:2018-10-25 13:30:20

标签: javascript angularjs checklist-model

我是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”]

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

角色:[“访客”,“管理员”,“用户”]

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

有人可以解释我在做什么错吗? 预先感谢。

1 个答案:

答案 0 :(得分:0)

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

相关问题