2017-09-20 32 views
1

我有Angular 1.5組件,它必須包含帶有ng選項的選擇下拉菜單。這個選擇必須被渲染到不同的控制器視圖中,並且在每個視圖中不同的數組值將被傳遞到組件中。

但我不知道如何將這個數組值從一個特定的視圖傳遞給組件。因此,可以說我有以下組成部分,其中arrayType中會是綁定到值和選項的排列將是結合了NG-選項:

app.test.component.js如何在Angular 1.5組件中使用ng-options?

(function() { 
angular 
    .module('Testcomponent') 
    .component('testSelector', { 
     controller: TestSelector, 
     templateUrl: 'test-selector.html', 
     bindings: { 
      model: '=', 
      form: '<', 
      name:'@', 
      arrayType: '<', 
      options: '=' 
     } 
    }); 
    function TestSelector() { 
    var vm = this; 
    } 

})(); 

和組件的HTML看起來像這樣:

app.test.component.html

<div> 
    <select class="select-form" 
     name="{{vm.name}}" 
     arrayType="{{vm.arrayType}}" 
     ng-model="vm.model" 
     ng-options="arrayType.value as arrayType.name for arrayType in 
     arrayType"> 
    </select> 
</div> 

而且在控制器的觀點我使用像這樣的組件:

app.test.controller.js

<test-selector 
     model="vm.something" 
     form="vm.TestForm" 
     name="Test Name" 
     array-type="vm.specificForTheControllerArray" 
     options="What options should I use here?"> 
    </test-selector> 

我如何可以將綁定在NG-選擇從組件是在控制器視圖中呈現,具體取決於每個視圖arrayType的具體情況?

任何幫助將不勝感激。

+1

我只是在這裏有一個評論,它不是在組件定義中使用雙向綁定的最佳實踐。 –

+1

謝謝!我同意,我應該想到不同的方法。 – Julsy

回答

1

您必須參考$ctrl或您在controllerAs選項中指定的任何內容以訪問控制器的綁定,在這種情況下:$ctrl.arrayType。另外,爲數組項目提供更一致的名稱。嘗試這樣的:

<select ... 
    ng-options="type.value as type.name for type in $ctrl.arrayType"> 
+0

謝謝!這是我錯過了 - 參考控制器。 – Julsy