Mikel
Mikel

Reputation: 117

Converting md-switch to md-select

I'm working on this dynamic filter system using AngularJs and trying to figure out how to convert the color and size options to be in two dropdowns (one for each category).

I've tried the following code which does successfully add the dropdown along with the options in the select box, but upon click of one of the options, it doesn't select it.

<md-select ng-model="filter[cat][value]" placeholder="val" multiple>
  <md-option ng-repeat="value in getItems(cat, data)" ng-value="{{value}}" ng-init="filter[cat]={}">
    {{value}}
  </md-option>
</md-select>

Demo: https://codepen.io/mikelkel/pen/rwQKRm (Above code had been removed from this demo.)

Upvotes: 0

Views: 149

Answers (2)

Chet
Chet

Reputation: 3729

There are a few issues:

According to the documentation, multiple is a boolean so it needs to be multiple="true".

value in ng-model doesn't exist in that scope since it only exists in md-option, so you can't do filter[cat][value]. If you look at the documentation for md-select you will see that when using multiple the model is an array. So if you set your ng-model to simply filter[cat] then its value will be something like ["red","yellow"].

You can then modify filterByPropertiesMatchingAND so that it does a string match against like properties (so if the shirt color is red and the filter.color array contains red then you would return true).

I forked your codepen (https://codepen.io/czema/pen/KqbpPE) and made the following changes:

Even though ng-init is frowned upon I left it, but I initialized the filter[cat] to an array rather than an object.

I removed the md-item.

I set ng-model to filter[cat] and multiple="true"

In the Javascript I modified your filterByPropertiesMatchingAND function. Now it expects $scope.filter contain arrays for each property (rather than an object with color names and boolean values). I dropped the noSubFilter function.

Upvotes: 1

Chet
Chet

Reputation: 3729

Use ng-options in select rather than ng-repeat on the option tag. The syntax for ng-options is a little odd, but it would be something like this in your case: ng-options="value for value in getItems(cat, data)"

Read the documentation for ngOption https://docs.angularjs.org/api/ng/directive/ngOptions

As far as why your attempt above doesn't work, probably has something to do with the ng-init, which is being executed for each option and is probably wiping out any existing data. Don't use ng-init.

Upvotes: 0

Related Questions