Mix Austria
Mix Austria

Reputation: 935

How to know add element to an array if checkbox is checked and remove it if unchecked?

Here is my code on HTML. I find it on google that I can use this.

<input type="checkbox" ng-true-value="addTitle(cpPortfolioItem)" ng-false-value="removeTitle(cpPortfolioItem)">

Here is my angularJS controller.

$scope.addTitle = function(cpPortfolioItem){
        $scope.selectedTitles.push(cpPortfolioItem.id);
        console.log('$scope.selectedTitles', $scope.selectedTitles);
     };

     $scope.removeTitle = function(cpPortfolioItem){
        $scope.selectedTitles.splice(cpPortfolioItem.id,1);
        console.log('$scope.selectedTitles', $scope.selectedTitles);
     };

it doesn't work. I have logged it in console but I can see it neither push or splice the array. Maybe ng-true-value is not a valid directive? Anyone can help me on this? I will really appreciate it.

Upvotes: 1

Views: 801

Answers (2)

User2
User2

Reputation: 1293

Use ng-change

<input type="checkbox" ng-change="titleChange()" ng-model="titleChanged">

In controller,

$scope.titleChanged = false;
$scope.titleChange = function() {
   if ($scope.titleChanged) {
      $scope.addTitle(cpPortfolioItem);
   } else {
      $scope.removeTitle(cpPortfolioItem);
   }
}

Working example:- http://jsfiddle.net/Shital_D/Lcumc3t7/10/

Upvotes: 0

Alvin Magalona
Alvin Magalona

Reputation: 771

Base on the documentation ng-true-value and ng-false-value value are not event handlers. These are the value set to the model when input is checked(ng-true-value) or unchecked(ng-false-value).

Use this instead or use ng-model and attach $watch to the model.

Upvotes: 2

Related Questions