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?
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? 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:
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.
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.
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.
The problem is that you $watch
ing 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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With