Recently delving into AngularJS, I encountered a puzzling issue with the Checklist-Model directive.
To replicate the problem, I followed one of their examples. Upon clicking a checkbox and invoking a function, the model reflects the update correctly on the template. However, upon inspecting the console log, I notice that the value of the clicked checkbox is missing. The oddity escalates when clicking the checkbox again - this time, the value disappears from the template but remains visible in the console.
Here's the snippet of code:
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:
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));
}
});
Upon clicking a checkbox for the first time, say 'User,' the console output shows:
Roles: ["guest","admin"]
Subsequently unchecking the same checkbox yields:
Roles: ["guest","admin","user"]
The application necessitates calling a function upon checkbox value change, which led me to utilize the "ng-change" directive.
If anyone can shed light on where I might be erring, it would be greatly appreciated. Thanks in advance.