Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$watch not working inside Angular Modal

I'm trying to put a $watch on a radio button inside AngularJS Modal. However $watch is not working inside modal for any value changes.

If I try to put the radio buttons outside modal, the $watch works perfectly fine.

http://plnkr.co/edit/q8t9qGJg57MMiQGop202?p=preview

In the above plunkr, if you click on Open me and select upper 2 radio buttons (me, you) $watch is not fired and in turn u cant see the alert with the value.

However if you click on radio buttons in the main page (i.e. Outside window) $watch works perfectly fine and throws alert message.

Does anyone have a workaround for this issue? Thanks

like image 676
nomad Avatar asked Dec 19 '22 16:12

nomad


1 Answers

This is a symptom of violating the unofficial golden rule when using ng-model:

Always have a "." in your ng-model expression

If you don't have a dot in your ng-model expression, it will create a property on the current scope at the point where the element with ng-model is. This will often not be the scope you are expecting, as many directives create child scopes, including the modal directive from UI Bootstrap.

By including a dot, you are referencing an object, which will be looked up on the prototype (scope) chain, and then accessing or creating a property on that, which will be on the correct scope.

Thus, in your example, if you change your code so that you create a $scope.data property in your controller, and set your ng-model expression to data.rdd, you will be able to "see" the changes in the controller and respond to them.

Thus the controller code function body starts with:

  $scope.data = {
    rdd: 'me'
  };

  $scope.$watch('data.rdd', function(v, old){
    if(v!==undefined && v !== old)
      alert(v);
  }); 

And your radio buttons in your HTML should be:

        <input type="radio" ng-model="data.rdd" value="me">me
        <input type="radio" ng-model="data.rdd" value="you">you

I forked your Plunkr so it now works.

like image 124
GregL Avatar answered Dec 22 '22 04:12

GregL