Saturday, 31 August 2013

AngularJS - ng-checked isn't triggering ng-change

AngularJS - ng-checked isn't triggering ng-change

Basically I have a table and each row have a text input and a checkbox,
the checkbox assign a default value to the input. The problem I'm having
is that I want to have a checkbox to check all checkboxes, and I've done
it, but it's not evaluating the expression in ngChange.
This is what I have:
1) Controller.js:
$scope.formData = {};
$scope.def_income = [];
$scope.master = false;
$scope.formData.income = [{ from:"", to:"", income:"" }]
$scope.addSal = function () {
this.formData.income.push({from:'',to:'',income:''});
};
$scope.delSal = function (index) {
if (index != 0) this.formData.income.splice(index,1);
}
$scope.masterToggle = function () {
this.master = this.master ? false : true;
}
$scope.defIncome = function (index) {
if (this.def_income[index]) this.formData.income[index].income="Default";
else this.formData.income[index].income = "";
}
2) index.html:
<a href="" ng-click="addSal()">Add</a>
<a href="" ng-model="master" ng-click="masterToggle()">Check all</a>
<table>
<thead>
<th>From</th>
<th>To</th>
<th>Income</th>
</thead>
<tbody>
<tr ng-repeat="income in formData.income">
<td><input kendo-date-picker class="form-control"
ng-model="income.from" placeholder="From" /></td>
<td><input kendo-date-picker class="form-control"
ng-model="income.to" /></td>
<td><input class="form-control" ng-model="income.income" /></td>
<td>Default income <input type="checkbox"
ng-model="def_income[$index]" ng-checked="master"
ng-change="defIncome($index)" /></td>
<td><a href="" ng-show="$index != 0"
ng-click="delSal($index)">Delete</a></td>
</tr>
</tbody>
</table>
The problem is that when masterToggle function is executed, it effectively
toggle the $scope.master value, and it's evaluated in ng-checked, the
checkboxes are checked, but the defIncome function that should be
evaluated when the checkbox value changes isn't.
Im really new to AngularJS (less than a week) so if I'm applying some bad
practices please feel free to point them out :)

No comments:

Post a Comment