I am using the following AngularJS code...
<div ng-controller="MyCtrl">
<h4>I have {{friends.length}} friends. They are...</h4>
<span id="selectall" ng-click="selectAllFriends()"><u>Select All</u></span> <br>
<ul class="example-animate-container">
<li class="animate-repeat" ng-repeat="friend in friends">
<input
type="checkbox"
value="{{friend.id}}"
ng-checked="friend.checked"
ng-model="friend.checked"
>
{{friend.id}} {{friend.name}} who is {{friend.age}} years old.
</li>
</ul>
<pre><strong>{{selectedFriends().length}} selected with filter:</strong> {{friends | filter:{checked:true} | json}}</pre>
<script>
function MyCtrl($scope, $filter) {
// fruits
$scope.friends = [
{id: 1, name:'John', age:25, gender:'boy'},
{id: 2, name:'Jessie', age:30, gender:'girl'},
{id: 3, name:'Johanna', age:28, gender:'girl'},
{id: 4, name:'Joy', age:15, gender:'girl'},
{id: 5, name:'Mary', age:28, gender:'girl'},
{id: 6, name:'Peter', age:95, gender:'boy'},
{id: 7, name:'Sebastian', age:50, gender:'boy'},
{id: 8, name:'Erika', age:27, gender:'girl'},
{id: 9, name:'Patrick', age:40, gender:'boy'},
{id: 10, name:'Samantha', age:60, gender:'girl'}
];
$scope.selectAllFriends = function() {
angular.forEach($scope.friends, function(friend){
friend.checked = true;
});
};
$scope.selectedFriends = function () {
return $filter('filter')($scope.friends, {checked: true});
};
}
</script>
here is jsfiddle
Select All function is working fine, but i want to add is: after clicking Select All, text of it should be changed to Deselect All and all checkbox should be deselected, i think it could be possible using toggle, please help me with this, thanks.
Your Span
<span id="selectall" ng-click="toggleSeleted()"><u>{{selectText}}</u></span>
And changes in comtroller...
$scope.allSelected = false;
$scope.selectText = "Select All";
$scope.toggleSeleted = function() {
$scope.allSelected = !$scope.allSelected;
angular.forEach($scope.friends, function(friend){
friend.checked = $scope.allSelected;
});
/*Change the text*/
if($scope.allSelected){
$scope.selectText = "Deselect All";
} else {
$scope.selectText = "Select All";
}
};
Here is a working Fiddle. Used two variables allSelected and selectText and changed them according to the selection.
$scope.selectAllFriends = function() {
angular.forEach($scope.friends, function(friend){
friend.checked = true;
});
};
Replace to :
$scope.isAll = false;
$scope.selectAllFriends = function() {
if($scope.isAll === false) {
angular.forEach($scope.friends, function(friend){
friend.checked = true;
});
$scope.isAll = true;
} else {
angular.forEach($scope.friends, function(friend){
friend.checked = false;
});
$scope.isAll = false;
}
};
DEMO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With