Angular directive not watching

89 Views Asked by At

I'm using a directive in AngularJS, and I'm trying to check if my field is $dirty, if that's true i want to log a message and when it changes i want to show another message (That sentence will be replaced later for something more complex).

I want to reuse in all my inputs my directive but i can't. Thanks in advance.

<input ng-edited ng-model="stakeholder.nombre" name="nombre" type="text">

And my directive is this:

MetronicApp.directive('ngEdited', function () {
    return {
        restrict: 'A',
        require: ['^form', 'ngModel'],
        link: function (scope, elem, attrs, req) {
            scope.elemDirty = req[1].$dirty;
            scope.elemName = req[1].$name;
            var doFunction = function () {
                if (scope.elemDirty) {
                    console.log("true");
                } else {
                    console.log("false");
                }
            };
            scope.$watch(scope.elemName, doFunction, true);
        }
    };
});
2

There are 2 best solutions below

2
On BEST ANSWER

Based on this answer, why not try

link: function (scope, elem, attrs, ngModel) {
    var doFunction = function (isDirty) {
        if (isDirty) {
            console.log("true");
        } else {
            console.log("false");
        }
    };
    scope.$watch(function(){return ngModel[1].$dirty;},doFunction);
}

See plunker

Edit

I noticed that in your question you are trying to watch change to the element's name. I'm not sure how you would be changing that attribute, but if you are, use attrs.$observe

attrs.$observe('name', doFunction);
2
On

If you're using a parameter (as opposed to a string), you need to return it from a function:

scope.$watch(function () {
    return scope.elemName;
}, doFunction, true);