观察指令属性

时间:2017-09-03 14:06:25

标签: javascript angularjs angularjs-directive angularjs-watch

我希望手表上有最大值,如果最大值的值发生变化则会发出警告

<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

1 个答案:

答案 0 :(得分:2)

请检查此工作代码。

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>