监视指令属性

watch on directive attribute

我想监视 max,如果 max 的值发生变化,它应该发出警报

<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 demo

请检查此工作代码。

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>