0

I know this question has been asked before, but none of the answers could help with my requirement.

I have a piece of code

<select ng-change ="loadHomePage()" ng-model="selectedPage" ng-options="x for x in pages"></select>

And my javascript looks something like this,

for (var i = 1; i<=response.data.pages; i++)
{
    $scope.pages.push(i);
}

My problem is that every time I run this code, it gives me a blank option. Which is fine, I can disable it from view by,

<option value="" hidden>

But my ng-model is such that after I select an option, the value gets reset to the default blank, i.e. null.

I want to take the option that I selected and keep ng-model set to that value. So it doesn't change any value for me.

I thought I could introduce another variable here, which could store the value of selectedPage, so it won't matter if the value of selected page gets changed, but it would be great if someone could tell me if there is a direct way.

4
  • Possible duplicate of Angular JS Remove Blank option from Select Option Commented Apr 28, 2018 at 5:21
  • @VipulSolanki Hey Vipul! I had previously checked out that answer, but couldn't find what I wanted! Commented Apr 28, 2018 at 5:24
  • try this: $scope.selectedPage = $scope.pages[0] after loop Commented Apr 28, 2018 at 5:28
  • Then what do you want? Commented Apr 28, 2018 at 5:37

1 Answer 1

1

First of want to say that try to use angular.forEach and avoid for loop. Also don't get your logic $scope.pages.push(i);, means are pushing the index?.
Please replace below answer and let me know if that's not what you want.

angular.forEach(response.data.pages, function(value, key) {
  if(value != ''){
      $scope.pages.push(value);
  }
}, $scope);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.