简体   繁体   中英

Angular ng model requires 2 click when using ng true and ng false

I'm using checkbox with ng model and ng-true-value and ng-false-value. It works fine but when its value comes 1 and it checked by default then it will take 2 clicks to change the value.

Is there any way to do it with first click

Code Example :

<input type="checkbox" ng-checked="CreateUpdateCat.IsDiscussionAllowed=='1'" ng-model="CreateUpdateCat.IsDiscussionAllowed" ng-true-value="1" ng-false-value="2" >

Controller Code :

angular.forEach($scope.CategoryData,function(v,k){
                        if(v.id == id)
                        {
$scope.CreateUpdateCat = {IsDiscussionAllowed:v.IsDiscussionAllowed,Name:v.Name};
};
});

here is plunkr url : https://plnkr.co/edit/JApepZfvNrlqDj9vine0?p=preview value is 1 by default but checkbox is not showing checked

Either use ng-checked or ng-model otherwise angular will get confused to do it. and it may be possible that you will get unpredicted results.

Do use only one directive ng-checked or ng-model

ng-checked should not be used with ng-model other wise you will get unexpected bihavior, ng-check docs: https://docs.angularjs.org/api/ng/directive/ngChecked

either use

 <input type="checkbox" ng-model="checkboxModel.value"
       ng-true-value="'YES'" ng-false-value="'NO'">

OR

<input type="checkbox" ng-checked="checkboxModel.value"
       ng-true-value="'YES'" ng-false-value="'NO'">

Try to put your input like this

<input type="checkbox" ng-model="CreateUpdateCat.IsDiscussionAllowed" ng-true-value="'1'" ng-false-value="'2'">

On your plunker, de scope CreateUpdateCat values are strings.

Some times angualrjs scope stays dirt, you may want to use this:

$timeout(function(){
  angular.forEach($scope.CategoryData,function(v,k){
   if(v.id == id){
      $scope.CreateUpdateCat = {IsDiscussionAllowed:v.IsDiscussionAllowed,Name:v.Name};
    };
  });
});

This way the model updates itself to the dom element's valeue

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