[英]Why $watch() can't work
我在我的主要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'}
});
我只想观看“ ng-minlength”的值状态。 我将此指令放在一个html文件中
HTML:
<input type="text" mymin ng-minlength=5>
<input type="text" mymin ng-minlength=13>
我以为,当我将焦点从一个输入更改为另一输入时,“ scope.min”的值将被更改,但是我错了。 “ scope.min”的值始终为13。
那你能告诉我原因吗? 非常感谢你。
如果您希望监视元素属性的变化,则应该使用$ observe而不是$ watch来监视属性对象(链接函数的第三个参数)
attrss.$observe("ng-minlength", function(n){
scope.min = n
})
您可以这样做:
如果要观看指令属性
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>
该行将创建一个mymin
指令,用于对此特定输入元素进行操作-此输入的min-length不会更改,始终为5。(您似乎假设该指令在您将其放置到的每个元素上都是相同的一个实例, 不是这种情况)
如果希望1个指令监视和管理每个输入的状态,请为包含所有这些输入的元素创建一个自定义指令。
如果要更新元素模糊的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.