简体   繁体   中英

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.

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.

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM