Search code examples
angularjsangularjs-ng-optionsangularjs-components

How to use ng-options inside Angular 1.5 component?


I have Angular 1.5 component which have to contain a select dropdown with ng-options. This select has to be rendered into different controller's views and in each view a different array of values would be passed into the component.

But I am not sure how to pass this array of values from a particular view to the component. So, lets say I have the following component, where arrayType would be the binding to the array of values and options would be the binding to the ng-options:

app.test.component.js

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

})();

And the html of the component looks like this:

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>

And the in the view of the controller I am using the component like so:

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>

How can I bind the ng-options from the component to be rendered in the view of the controller depending on the specific for each view arrayType?

Any help would be greatly appreciated.


Solution

  • You have to refer to $ctrl or whatever you've specified in the controllerAs option in order to access the controller's bindings, in this case: $ctrl.arrayType. Also, give a more consistent name for the array item. Try something like this:

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