2014-01-15 54 views
0

我想拉一個角度JS指令作爲屬性使用的變量。Angular JS屬性指令採取變量

我們以petFilter爲例。

HTML:

<input type="text" name="catName" pet-filter='cat'> 
<input type="text" name="dogName" pet-filter='dog'> 

所以,如果我輸入 '狡猾' 和 '布朗尼' 到兩個輸入端,我要離開:

Foxy is a cat! 
Brownie is a dog! 

我至今是:

JS:

.directive('petFilter', function(){ 
    return { 
     restrict: 'A', 
     require : 'ngModel', 
     scope : true, 
     link: function($scope, elem, attrs, ctrl){ 
      $scope.$watch(attrs.ngModel, function() { 
       var temp = ctrl.$viewValue; 
       var petType = ????; 
       outputFunction(temp + 'is a ' + petType + '!'); 
      }) 
     } 
    }; 
}) 

我只是卡在如何設置值petType

+0

也許是:VAR petType = scope.model [attrs.pet過濾器]); –

回答

3

對於您的示例,您實際上並不需要$ watch,該值是綁定到作用域上的變量的。值「狗」和貓」位於被傳遞在ATTRS,而你的情況看起來像:

{ 
    petFilter: "cat" 
} 

,或者如果你使用不同的屬性一樣,它看起來像:

{ 
    petType: "dog" 
} 

所以使用它在你的指令,你可以從ATTRS訪問對象,像這樣:

.directive('petFilter', function(){ 
    return { 
     restrict: 'A', 
     require : 'ngModel', 
     scope : true, 
     link: function($scope, elem, attrs, ctrl){ 
      var petType = attrs.petFilter; 

      outputFunction(temp + 'is a ' + petType + '!'); 
     } 
    }; 
}) 

編輯:如果你想觀看基於NG-模型上的範圍屬性指令,你是關閉,你所要做的就是添加$ watch回調的參數。在這個例子中,假設你的投入是這樣的:

<input ng-model="petName" petFilter="cat"> 

那麼你的指令應該是這樣的:

.directive('petFilter', function(){ 
    return { 
     restrict: 'A', 
     require : 'ngModel', 
     scope : true, 
     link: function($scope, elem, attrs){ 
      /** The callback we pass in here is called every time the value of the 
       scope expression, which in this case is "petName", changes. **/ 
      $scope.$watch(attrs.ngModel, function (newValue, oldValue) { 

       /** newValue will be equal to $scope.petName. **/ 
       var temp = newValue; 
       var petType = attrs.petFilter; 
       outputFunction(temp + 'is a ' + petType + '!'); 
      }) 
     } 
    }; 
}) 
+0

這是一個簡化版本。爲了擴展我正在努力的方向,當有人輸入'Foxy'時,他們會得到:「F是一隻貓!」那麼「佛是一隻貓!」那麼'狐狸是一隻貓!'然後'狡猾是一隻貓!'這就是爲什麼我要買一塊手錶 - 我希望它在輸入文本的時候改變,至於其他的,我會給它一個! –

+0

不得不交換'oldValue'和'newValue',但是那樣做了訣竅!非常感謝! –

+0

它們實際上是按照正確的順序排列的,但是第一次在初始化過程中調用這兩個值是相等的,所以你可以做一個(newValue!== oldValue)檢查確保它不是第一次運行 – ilmatic