Sidd Thota
Sidd Thota

Reputation: 2249

How to Remove specific element ng-option list if it's not matching ng-model

I'm trying to remove a specific element from Select Dropdown list which I take from ng-options.

I get data onto UI through ng-model and then I wanted to display that data in the dropdown using ng-options.

I'm trying to remove the "No Minimum Age" option from the list, if the Age isn't 0.

<select name="ageField" ng-model="minAge" ng-options="minAge.value as minAge.key for minAge in minAgeList">

Reference: http://embed.plnkr.co/83NKDa/

In this example, I'm setting the minAge as 0 in the controller, but if the data is other than 0, I wanted to remove the No Minimum Age option from the list.

Upvotes: 0

Views: 802

Answers (3)

Anil Yadav
Anil Yadav

Reputation: 1096

Try with option tag inside the select tag and based on condition ng-show , ng-if to show hide option dropdown.

I hope it fix your problem you can pass the ng-show value based on minAgeList value remove the first object option from the minAgelist and put valid valid value which you want.

<select name="ageField" ng-model="minAge" ng-options="minAge.value as minAge.key for minAge in minAgeList">
       <option ng-show="false" value="">-- choose an option --</option>
    </select>

Sorry for the bad english ;)

Upvotes: 0

William B
William B

Reputation: 1419

No need to change the minAgeData factory. Just take a slice of minAgeData() in your controller:

// skip index 0 if `minAge` is not 0
var startIndex = $scope.minAge !== 0 ? 1 : 0;
$scope.minAgeList = dataFact.dataDetails.minAgeData().slice(startIndex);

See here: https://plnkr.co/edit/hOVg2WWq4eKPLeHuL9YA?p=preview

Upvotes: 1

Anvesh P
Anvesh P

Reputation: 299

Pass the min age value to the minAgeData function and check the value before push the values to the array.

var app = angular.module('myApp', []);

app.controller('demoCtrl', function ($scope, $http, dataFact) {
    $scope.minAge = 1;
    $scope.maxAge = 99;
    **$scope.minAgeList = dataFact.dataDetails.minAgeData($scope.minAge);**


});

app.factory('dataFact', dataFact);
    function dataFact() {
  var minAgeData = function (pValue) {
            var minAgeArray = [];
            **if (!pValue){
                minAgeArray.push({
                    "value": 0,
                    "key": "No Minimum Age"
                });
            }**
            for (var i = 1; i <= 115; i++) {
                var label = i;
                if (i < 10) {
                    label = "0" + i;
                }

                minAgeArray.push({
                    "value": i,
                    "key": label
                })
            }

            return minAgeArray;
        };

        var service = {
          dataDetails: { 
            minAgeData: minAgeData
          }
        }
        return service;
}

Upvotes: 3

Related Questions