2

我似乎無法將我的想法包括在我如何解決這個問題中。我有一個指令,它看起來如下:AngularJS將一個屬性值作爲參數傳遞給一個函數,該函數被ng-change所調用

.directive('seqWidget', ['Sequence', function(Sequence){ 
    return {   
     restrict: 'E', 
     scope: { 
      placeholder: '@', 
      option: '@' 
     }, 
     template: '<fieldset><legend data-ng-transclude></legend><input type="text" placeholder = {{placeholder}} autofocus data-ng-model="index" data-ng-change="retrieve({{option}});"/>{{output}}</fieldset>', 
     replace: true, 
     transclude: true, 
     link: function ($scope, $elem, $attr){ 

      $scope.retrieve = function(key){ 
       //var option = $attr.option; 
       console.log(key); 
      } 
     } 
    } 
}]); 

我的HTML是這樣的:

<seq-widget placeholder="Index 0-400" option="accurate">Which index number would you like to gain accuracy on?</seq-widget> 

我試圖完成基於屬性改變我的函數調用的動態方式等幾種方式值。我會使用'&'前綴,但我希望此功能在輸入發生更改時被觸發。有沒有一種實際的方式來實現我想要做的事情?或者是否需要使用jQuery來說出類似於$('input')的內容。on('change',function(){});在我的鏈接功能?

回答

2

您不必通過option它已經在範圍內,而您設置了文本綁定option: '@'

所以只是做: -

 $scope.retrieve = function(key){ 
      console.log($scope.option); 
     } 

它也將工作,如果你刪除插值,你不必在一個表達式內插範圍的變量。

data-ng-change="retrieve(option);" 
+0

即使在我從「retrieve()」中刪除「option」作爲參數並且在我的console.log($ scope.option)中執行了操作後,我仍然得到了「undefined」的控制檯日誌$ scope.retrieve函數定義在我的指令的鏈接函數中,就像你演示的一樣。 – papiro 2014-10-19 00:07:55

+0

你可能做錯了,檢查這個http://plnkr.co/edit/X1LnFy?p=preview – PSL 2014-10-19 00:10:16

+0

,而且,爲了訪問option屬性的值(在這種情況下是「準確的」),我相信你必須使用插值作爲準確變得可用作爲字符串...就像中的「佔位符」的值被插入到模板的新佔位符屬性中一樣。 – papiro 2014-10-19 00:11:40

相關問題