簡體   English   中英

監視指令屬性

[英]watch on directive attribute

我想監視最大,如果最大的值發生變化,則它應該發出警報

<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);
        });
    }

我不知道我在做什么錯。 我嘗試了$ watch和$ observe,但是都沒有用。 請任何人都可以幫助。

JS FIDDLE演示

請檢查此工作代碼。

 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