Andres
Andres

Reputation: 4501

angular select with custom option template

I have one select which show a list of objects and a button to show the object selected data. It works.

The problem is that I need to show more than the object name into the select box, I tried this but it return an string instead of a json object:

<select ng-model="selected">
    <option ng-repeat="item in items" value="{{item}}">
          {{item.name}} <span>Some nice data</span>
    </option>
</select>

How can I get it? do I have to create a directive for it?

Here my code which works without additional data into the select box

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


app.controller('Test', function($scope) {

  $scope.selected = null;
  $scope.items = [{
    name: 'a',
    value: 1,
    something: "xyz"
  }, {
    name: 'b',
    value: 2,
    something: "xyz"
  }, {
    name: 'c',
    value: 3,
    something: "xyz"
  }]


  $scope.show = function() {
    alert("selectec " + $scope.selected.name + ' with value ' + $scope.selected.value);
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<html ng-app="app">

<body>
  <div ng-controller="Test">
    <select data-ng-options="i.name for i in items" ng-model="selected">
    </select>
    <button ng-click="show()">press</button>
  </div>
</body>

</html>

Upvotes: 2

Views: 9163

Answers (2)

Thiago Negri
Thiago Negri

Reputation: 5351

You can't output HTML from the ngOptions AngularJS directive. But you can customize the option content using a function to label the elements, like so (notice that the HTML is escaped):

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


app.controller('Test', function($scope) {

  $scope.selected = null;
  $scope.items = [{
    name: 'a',
    value: 1,
    something: "xyz"
  }, {
    name: 'b',
    value: 2,
    something: "xyz"
  }, {
    name: 'c',
    value: 3,
    something: "xyz"
  }]


  $scope.show = function() {
    alert("selectec " + $scope.selected.name + ' with value ' + $scope.selected.value);
  }

  $scope.format = function(i) {
    return i.name + '<span>Some nice data</span>';
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<html ng-app="app">

<body>
  <div ng-controller="Test">
    <select data-ng-options="i as format(i) for i in items" ng-model="selected">
    </select>
    <button ng-click="show()">press</button>
  </div>
</body>

</html>

Upvotes: 6

Scott
Scott

Reputation: 1690

It's not valid to put HTML inside of an option tag for a select. You'll just need to create your own using DIV tags or whatever suits your needs. On another note you may want to rethink your UI as the purpose of a drowdown is not to be browsing data

Upvotes: 1

Related Questions