LoginSignup
5
5

More than 5 years have passed since last update.

AngularJSのngOptionsで表示をカスタマイズするメモ

Posted at

Plunkr

ngOptionsでasなどを使うとオブジェクトのフィールドを選んだりできるが、ちょっと凝ったフォーマットにしたい場合は、スコープのメソッドを使える。

template
  <body ng-controller="TestCtrl as test">
    <select ng-model="test.selectedItem"
      ng-options="item as test.formatItem(item) for item in test.items">
    </select>
  </body>
controller
myApp.controller('TestCtrl',  function() {
  this.items = [
      {name:'foo', age:'25'},
      {name:'bar', age:'14'}
    ];

  this.formatItem = function(item) {
    return item.name + ' (' + item.age + ')';
  };

  this.selectedItem = null;
});

ngOptionsで、リストのインデックスを使いたい場合、次のように(index, item)のようにすると、indexに配列のインデックスが入る。

template
    <select ng-model="test.selectedItem"
      ng-options="item as test.formatItem(index, item) for (index, item) in test.items">
    </select>
controller
  this.formatItem = function(index, item) {
    return '[' + index + '] ' + item.name + ' (' + item.age + ')';
  };
5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5