angularjs - Update a model by unchecking a checkbox with a directive -


so i'm trying make dependency checkboxes. dependent checkbox disabled + unchecked once checkbox dependent upon uncheck. reason, unchecking checkbox inside directive job, in disabling , unchecking model binded not update.

html:

<div>   <input type="checkbox" data-ng-model="test.dependency"/>   <span>unchecking 1 disable next</span> </div>  <div>   <input dependent="test.dependency" type="checkbox" data-ng-model="test.optional" />   <span>this checkboxs directive uncheck when first 1 unchecked, model doesn't updated, not it's {{test.optional}}</span> </div> 

controller (for defaults options):

$scope.test = {   dependency: true,   optional: false } 

directive:

restrict: 'a', link: function(scope,elem,attrs){   scope.$watch(attrs.dependent,function(val){     if (!val){       elem[0].checked = false;       elem[0].disabled = true     } else {       elem[0].disabled = false     }   }) } 

edit: right, here's plunk.

since you're applying directive element uses ng-model directive, need tell ng-model update model , view:

app.directive('dependent', function(){   return {     restrict: 'a',     require: 'ngmodel', // requires ngmodelcontroller injected     link: function(scope,elem,attrs, ngmodelctrl){       scope.$watch(attrs.dependent, function(val){         if (!val) {           elem[0].disabled = true;           ngmodelctrl.$setviewvalue(); // updates model           ngmodelctrl.$render();       // updates view          } else {           elem[0].disabled = false         }       });     }   } }); 

plunker here.

check out ngmodelcontroller documentation more details.


Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -