簡體   English   中英

AngularJS-Checklist-Model在復選框更改時無法正確更新模型

[英]AngularJS - Checklist-Model doesn't update the model correctly on checkbox change

我是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));
  }
});

我第一次單擊復選框,即“用戶”,控制台上的輸出為:

角色:[“來賓”,“管理員”]

然后,當我取消選中同一復選框時,輸出為:

角色:[“訪客”,“管理員”,“用戶”]

在我正在開發的應用程序中,當復選框更改其值時,我必須調用一個函數,這就是為什么我使用“ ng-change”指令。

有人可以解釋我在做什么錯嗎? 提前致謝。

checklist-model,它在復選框中使用了Id作為checklist-value ,在代碼中使用了文本。 因此在函數$ scope.checkAll中,您應該返回item.text而不是item.id ;在函數$ scope.checkFirst中,您應推送$ scope.roles.find(item => item.id == 1).text其余的似乎正確

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM