Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Sticky" select in Angular app

I have an annoying issue with an app that has an Angular-based frontend. A certain select box is "sticky" - you have to select an option twice to change to it. Here's a snippet which reproduces the issue:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script>
  var app = angular.module('myapp', []);

  app.controller('NewsCtrl', function($scope) {
    // Set news data
    $scope.news = {
      specific_for_dealership: '003'
    };

    // Get dealers
    $scope.dealers = [{
      id: 1,
      dealerid: '001',
      name: 'Volvo'
    }, {
      id: 2,
      dealerid: '002',
      name: 'Saab'
    }, {
      id: 3,
      dealerid: '003',
      name: 'Seat'
    }];
  });
</script>
<div ng-app="myapp">
  <div ng-controller="NewsCtrl">
    <form>
      <select name="specific_for_dealership" ng-model="news.specific_for_dealership">
        <option value="">All</option>
        <option ng-repeat="dealer in dealers" ng-selected="news.specific_for_dealership" value="{{ dealer.dealerid }}">{{ dealer.name }}</option>
      </select>
    </form>
  </div>
</div>

Any idea what has gone wrong and how I might resolve this?

like image 580
Matthew Daly Avatar asked Jun 16 '26 23:06

Matthew Daly


1 Answers

You do not need to use ng-selected to select your option, ng-model does that for you.

It is causing the model to get confused. Which is why you have to select it twice.

 <select name="specific_for_dealership" ng-model="news.specific_for_dealership">
        <option value="">All</option>
        <option ng-repeat="dealer in dealers"  value="{{ dealer.dealerid }}">{{ dealer.name }}</option>
 </select>

Something else I would personally recommend as well is switching to ng-options to display your options list from the object. It will give you some more versatility. For example you can bind the whole object to the selector instead of just the ID.

<select name="specific_for_dealership" 
     ng-options="dealer.dealerid as dealer.name for dealer in dealers" 
     ng-model="news.specific_for_dealership">
        <option value="">All</option>
</select>
like image 92
Malkus Avatar answered Jun 19 '26 12:06

Malkus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!