Siddhartha Thota Siddhartha Thota - 1 month ago 6
Javascript Question

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.

Answer

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;
}