简体   繁体   English

为什么$ watch()无法工作

[英]Why $watch() can't work

I created a angular directive in my main javascript file. 我在我的主要javascript文件中创建了angular指令。

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". 我只想观看“ ng-minlength”的值状态。 I put this directive in one html file 我将此指令放在一个html文件中

Html: 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. 我以为,当我将焦点从一个输入更改为另一输入时,“ scope.min”的值将被更改,但是我错了。 The value of "scope.min" is alway 13. “ scope.min”的值始终为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) 如果您希望监视元素属性的变化,则应该使用$ observe而不是$ watch来监视属性对象(链接函数的第三个参数)

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) 该行将创建一个mymin指令,用于对此特定输入元素进行操作-此输入的min-length不会更改,始终为5。(您似乎假设该指令在您将其放置到的每个元素上都是相同的一个实例, 不是这种情况)

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. 如果希望1个指令监视和管理每个输入的状态,请为包含所有这些输入的元素创建一个自定义指令。

If you want to update scope.min of blur of the element, use a blur event handler 如果要更新元素模糊的scope.min ,请使用模糊事件处理程序

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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