I've got an AngularJS attribute directive, and I would like to take an action any time its parent input's value changes. Right now I'm doing it with jQuery:
angular.module("myDirective", [])
.directive("myDirective", function()
{
return {
restrict: "A",
scope:
{
myDirective: "=myDirective"
},
link: function(scope, element, attrs)
{
element.keypress(function()
{
// do stuff
});
}
};
});
Is there a way to do this without jQuery? I'm finding the keyPress event isn't doing exactly what I want it to, and while I'm sure I'll come up with a solution, I get a little nervous when I resort to using jQuery in an Angular project.
So what's the Angular way to do this?
This question is related to
jquery
angularjs
attributes
directive
Since this must have an input element as a parent, you could just use
<input type="text" ng-model="foo" ng-change="myOnChangeFunction()">
Alternatively, you could use the ngModelController
and add a function to $formatters
, which executes functions on input change. See http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController
.directive("myDirective", function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attr, ngModel) {
ngModel.$formatters.push(function(value) {
// Do stuff here, and return the formatted value.
});
};
};
To watch out the runtime changes in value of a custom directive, use $observe
method of attrs
object, instead of putting $watch
inside a custom directive.
Here is the documentation for the same ... $observe docs
Source: Stackoverflow.com