简体   繁体   English

监视指令属性

[英]watch on directive attribute

I want to have a watch on max, if value of max changes then it should alert 我想监视最大,如果最大的值发生变化,则它应该发出警报

<div ng-controller='MyController' ng-app="myApp">
<div>{{title}}</div>
<input id='txt' type='text' max="{{max}}" value="{{max}}" foo/>
<input type="button" ng-click="changeMax()" value='change max' />

 scope: {
        max: '@',
    },
    link: function(scope, element, attrs) {
        /*scope.$watch(attrs.max, function() {
            alert('max changed to ' + max);
        });*/

        attrs.$observe('max', function(val) {
            alert('max changed to ' + max);
        });
    }

I have no idea what mistake I am doing. 我不知道我在做什么错。 I tried both $watch and $observe but non worked. 我尝试了$ watch和$ observe,但是都没有用。 Please anyone can help. 请任何人都可以帮助。

JS FIDDLE demo JS FIDDLE演示

Please check this working code. 请检查此工作代码。

 var app = angular.module('myApp', []); app.directive('foo', function() { return { restrict: 'EA', scope: { max: '@', }, link: function(scope, element, attrs) { /*scope.$watch(attrs.max, function() { alert('max changed to ' + max); });*/ attrs.$observe('max', function(val) { alert('max changed to ' + val); }); } } }); app.controller('MyController', ['$scope', function($scope) { $scope.title = 'Hello world'; $scope.max = 4; $scope.changeMax = function() { $scope.max += Math.floor(Math.random() * 10); } }]); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.14/angular.min.js" ></script> <div ng-controller='MyController' ng-app="myApp"> <div>{{title}}</div> <input id='txt' type='text' max="{{max}}" value="{{max}}" foo/> <input type="button" ng-click="changeMax()" value='change max' /> </div> 

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

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