简体   繁体   中英

Why $watch() can't work

I created a angular directive in my main javascript file.

myApp.directive('mymin', function(){
var func = function(scope, im, attrss, c){
    scope.$watch(function(){ return im.attr('ng-minlength') }, function(n){
        scope.min = n
    })
    }
    return {link:func, restrict: 'A'}
});

I just want to watch the value state of "ng-minlength". I put this directive in one html file

Html:

<input type="text" mymin ng-minlength=5>
<input type="text" mymin ng-minlength=13>

I thought that when I change the focus from one input to another one, the value of "scope.min" will be changed, but i am wrong. The value of "scope.min" is alway 13.

So could you tell me the reason? Thank you very much.

If you wish to watch for changes on element attributes then rather than $watch you should be using $observe on the attributes object(The third parameter of the link function)

attrss.$observe("ng-minlength", function(n){
    scope.min = n
})

you can do rather like this:-

If you want to watch directive attribute

myApp.directive('mymin', function(){
var func = function(scope, im, attrss, c){
    scope.$watch('ngMinlength', function(n){
        scope.min = n
    })
    }
    return {link:func, restrict: 'A'}
});

<input type="text" mymin ng-minlength=5>

This line will create a mymin directive acting for this particular input element - the min-length on this input will not change, it's always 5. (You seem to assume that the directive will be the same one instance on every element you place it on, this is not the case)

If you want 1 directive to watch and manage the state of every input, create a custom directive for the element containing all these inputs.

If you want to update scope.min of blur of the element, use a blur event handler

 var app = angular.module('my-app', [], function() {}) app.controller('AppController', function($scope) { $scope.message = "Welcome"; }); app.directive('mymin', function() { var func = function(scope, im, attrss, c) { angular.element(im).on('blur', function() { scope.min = im.attr('ng-minlength'); scope.$apply(); }) } return { link: func, restrict: 'A' } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="my-app"> <div ng-controller="AppController"> <p>{{min}}</p> <input type="text" mymin ng-minlength=5 /> <input type="text" mymin ng-minlength=13 /> </div> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM