0

我希望有最大的手錶,如果最大的值,那麼改變它應提醒手錶上的指令屬性

<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

回答

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>

+0

什麼是錯在我的代碼? –

+0

foo指令:剛刪除$ watch並替換alert('max已更改爲'+ max);通過alert('max changed to'+ val); –

+0

@VarunSukheja:如果它解決了您的問題,請將其標記爲答案 –