3

我正在構建一個使用自定義指令的輸入過濾的可單擊選項列表。Angular Custom Directives:使用鏈接函數內的參數調用一個函數

HTML:

<combobox 
    input-model="myModel" 
    options="myList" 
    option-label="label" 
    option-select="selectFn()"></combobox> 

的指令(簡體):

app.directive("combobox", function() { 
    return { 
     restrict: "E", 
     replace: true, 
     template: "<input type=‘text’ ng-model=‘inputModel’ />" + 
         "<button ng-repeat='option in options | " + 
             "filter: inputModel’" + 
           "ng-mousedown=‘optionSelected(option)’" + 
         ">{{option[optionLabel]}}</button>", 
     scope: { 
      inputModel: "=", 
      options: "=", 
      optionLabel: "@", 
      optionSelect: "&" 
     }, 
     link: function(scope, elem, attrs) { 
      scope.optionSelected = function(option) { 
       // some stuff here... 
       scope.optionSelect(); 
      } 
     } 
    } 
}) 

範圍:

$scope.myList = [ 
    { label: "First Option", value: 1 }, 
    { label: "Second Option", value: 2 }, 
    { label: "Second Option", value: 2 } 
] 
$scope.selectFn() = function() { 
    // doing stuff here... 
} 

但我想打電話給selectFn與調用它的選項屬性。喜歡的東西:

option-select=「selectFn(option.value)」 

scope.optionSelect(option); 

這可能嗎?我可以在範圍內調用函數並從鏈接函數內傳遞參數嗎?

由於定製原因,我不能使用組合框庫,如ui-select。

回答

1

您正在傳遞函數的結果,在父範圍中評估,而不是fu nction本身。你可以評估你的表達,然後執行結果函數。

所以,你應該嘗試是這樣的

<combobox 
    input-model="myModel" 
    options="myList" 
    option-label="label" 
    option-select="selectFn"> 
在您的標記

,然後在你的指令

link: function(scope, elem, attrs) { 
     scope.optionSelected = function(option) { 
      // some stuff here... 
      scope.optionSelect()(option); 
     } 
    } 

注意,在option-select="selectFn"表達就交給包裹在您的分離範圍功能optionSelect。當你評估它時,你會得到你想要的功能。這就是爲什麼你使用scope.optionSelect()(option)

見你的指令,在這裏工作:http://plnkr.co/edit/zGymbiSYgnt4IJFfvJ6G

https://docs.angularjs.org/api/ng/service/$compile

&或& ATTR - 提供了一種在 父作用域上下文中執行的表達式。如果未指定attr名稱,則假定屬性名稱 與本地名稱相同。給定範圍的小部件定義:{ localFn:'& myAttr'},那麼隔離範圍屬性localFn將指向 count = count + value表達式的函數包裝。通常, 希望通過表達式 將數據從隔離範圍傳遞到父範圍,這可以通過將本地 變量名稱和值的映射傳遞到表達式包裝函數fn來完成。例如, 如果表達式爲增量(量),那麼我們可以通過調用localFn如localFn({量:22})指定的金額 值

1

你應該這樣調用你的指令中:

scope.optionSelect({ 
    data: [] 
}); 

你的模板(對象將是與數據數組對象):

option-select="functionToCall(object)" 
在你的控制器

然後:

$scope.functionToCall = function(object){ 
    console.log(object); 
    //will output: [] 
}