[英]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.