Angular $q synchronous .then
attach .then handler after the promise was created
by Kyrylo Slatin
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular-resource.js"></script>
<div ng-controller="ctrl">
<input type="checkbox" id="cbxSelectAllPreventive" ng-model="checked" ng-change="setAll(checked)"/> <label for="cbxSelectAllPreventive">{{selectLabel}}</label>
<ul style="list-style: none;">
<li ng-repeat="test in lists.Tests">
<input type="checkbox" ng-model="test.isSelected"/>{{test.text}}--{{test.isSelected}}
</li>
</ul>
</div>
JavaScript
angular.module('app', ['ngResource']);
angular.module('app').controller('ctrl', function ($scope, $q, $timeout) {
$scope.selectLabel = 'Select All';
$scope.setAll = function(isSelected){
$scope.selectLabel = isSelected ? 'Deselect All' : 'Select All';
$scope.lists.Tests.map(function(el){
el.isSelected = isSelected;
})
}
$scope.lists = {Tests:[
{isSelected: false, text: 'A'},
{isSelected: false, text: 'B'},
{isSelected: false, text: 'C'},
{isSelected: false, text: 'D'},
]};
$scope.$watch('lists.Tests', function(){
var text = $scope.lists.Tests.map(function(el){ return el.isSelected; }).join();
console.log(text);
var allSelected = $scope.lists.Tests.every(function(el){ return el.isSelected;});
var noneSelected = $scope.lists.Tests.every(function(el){ return !el.isSelected;});
if(noneSelected){
$scope.selectLabel = 'Select All';
$scope.checked = false;
}else if(allSelected){
$scope.selectLabel = 'Deselect All';
$scope.checked = true;
}
if(!noneSelected && !allSelected) {
$scope.selectLabel = 'Undetermined';
// here set the check box to undetermined (third) state
}
}, true);
});
angular.bootstrap(document, ['app']);