Mohit Bumb
Mohit Bumb

Reputation: 2493

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

Upvotes: 0

Views: 540

Answers (4)

Utku Apaydin
Utku Apaydin

Reputation: 162

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

Upvotes: 0

Roth
Roth

Reputation: 138

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.

Upvotes: 0

Saurabh Agrawal
Saurabh Agrawal

Reputation: 7739

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

Upvotes: 2

Elgayed
Elgayed

Reputation: 1219

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'">

Upvotes: 0

Related Questions