Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$watch ngModel from inside directive using isolate scope

I am trying to watch my model value from inside my linking function.

scope.$watch(attrs.ngModel, function() {
       console.log("Changed"); 
    });

When I change the model value inside my controller, the $watch function is not triggered.

$scope.myModel = "ACT";

$timeout(function() {
   $scope.myModel = "TOTALS"; 
}, 2000);

Fiddle: http://jsfiddle.net/dkrotts/BtrZH/4/

What am I missing here?

like image 269
Dustin Avatar asked Feb 04 '13 18:02

Dustin


People also ask

How do I isolate the scope in a directive?

Isolating the scope in a directive is a is a simple process. Start by adding a scope property into the directive as shown next. This automatically isolates the directive’s scope from any parent scope (s). Now that the scope is isolated, the customer object from the parent scope will no longer be accessible.

What is isolate scope in AngularJS?

What is Isolate Scope? Directives have access to the parent scope by default in AngularJS applications. For example, the following directive relies on the parent scope to write out a customer object’s name and street properties:

How do I define a property in the isolate scope?

Here’s an example of a directive that uses the = local scope property to define a property in the isolate scope. In this example the directive takes the object provided to the customer property and iterates through all of the properties in the object using ng-repeat. It then writes out the property values using <li> elements.

What is an isolate scope in Salesforce directive?

The directive code creates an isolate scope that allows a name property to be bound to a value that is passed in from the “outside world”: Notice how the $scope.customer.name value from the controller is bound to the name property of the directive’s isolate scope.


2 Answers

You'll need to watch a function that returns the $modelValue you're watching.

The following code shows a basic example:

app.directive('myDirective', function (){
    return {
        require: 'ngModel',
        link: function(scope, element, attrs, ngModel) {
           scope.$watch(function () {
              return ngModel.$modelValue;
           }, function(newValue) {
               console.log(newValue);
           });
        }
     };
});

Here's a plunker of the same idea in action.

like image 163
Ben Lesh Avatar answered Sep 28 '22 09:09

Ben Lesh


The problem is that you $watching attrs.ngModel which is equal to "myModel". You do not have "myModel" bound in your scope. You want to $watch "model". That is what is bound in the scope of your directive. See http://jsfiddle.net/BtrZH/5/

like image 33
dnc253 Avatar answered Sep 28 '22 09:09

dnc253