javascriptangularjsangularjs-directiveangularjs-watch

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. Please anyone can help.

JS FIDDLE demo


Solution

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