diegoaguilar
diegoaguilar

Reputation: 8376

How to conditionally set ng-options for Angular JS?

Use case:

I have a web form, a user can select a category, and upon the selected one a <select> with proper subcategories will be shown.

Now I'm using ng-if directive per each case so the markup block will be rendered only after another variable.

This my markup:

    <select class="form-control" ng-if="products.newProduct.category=='PTR'" ng-model="products.newProduct.data.subcategory" ng-options="type for type in products.subcategories.ptr"></select>

   <select class="form-control" ng-if="products.newProduct.category=='Losacero'" ng-model="products.newProduct.data.subcategory" ng-options="type for type in products.subcategories.losacero"></select>
  
   <select class="form-control" ng-if="products.newProduct.category=='Varilla'" ng-model="products.newProduct.data.subcategory" ng-options="type for type in products.subcategories.varilla"></select>

But I think this is just too verbose, is there any way to make this more elegant and shorten the markup?

Upvotes: 1

Views: 844

Answers (1)

Marc Kline
Marc Kline

Reputation: 9409

This is a good case for a reusable directive. At least here your view would be more DRY and tidy:

<sub-select products="products" label="PTR" prop="ptr"></sub-select>
<sub-select products="products" label="Losacero" prop="losacero"></sub-select>
<sub-select products="products" label="Varilla" prop="varilla"></sub-select>

The directive definition might look like:

.directive('subSelect', function(){
  return {
    restrict: 'E',
    replace: true,
    scope: {
      label: '@',
      prop: '@',
      products: '='
    },
    template: '<select class="form-control" ng-if="products.newProduct.category === label" ng-model="products.newProduct.data.subcategory" ng-options="type for type in products.subcategories.{{prop}}"></select>'
  }
})

Demo

Upvotes: 2

Related Questions