How to display only visible items in AngularJs dropdown

I have an AngularJs object:

$scope.control = {'options': [{ "id": 1, "text": "Option 1", "isHidden": 0 }, { "id": 2, "text": "Option 2", "isHidden": 1 }, { "id": 3, "text": "Option 3", "isHidden": 0 }]};

      

Now I can display a dropdown list with all items using the following command:

<select ng-model="control.uiSelValue" ng-options="option.text for option in control.options" class="form-control"></select>

      

How can I only display items that are marked as "isHidden = 0"? , that is, I only want to display "Option 1" and "Option 3" only in the dropdown.

+3


source to share


1 answer


Apply a custom filter to control.options

. You don't really need to create this filter as you can use an expression, but I think it's bad practice to do too much logic in the view.

For example:

Demo

View



<select ng-model="control.uiSelValue"
        ng-options="option.text for option in control.options | filter:myFilter"
        class="form-control">
</select>

      

controller

$scope.control = {
    options: [{
        "id": 1,
        "text": "Option 1",
        "isHidden": 0
    }, {
        "id": 2,
        "text": "Option 2",
        "isHidden": 1
    }, {
        "id": 3,
        "text": "Option 3",
        "isHidden": 0
    }]
};

$scope.myFilter = function (value) {
    return value.isHidden === 0;
};

      

+3


source







All Articles