角度选择与自定义选项模板

And*_*res 2 javascript select angularjs

我有一个选择显示对象列表和一个按钮来显示对象选定的数据.有用.

问题是我需要在选择框中显示超过对象名称,我试过这个但它返回一个字符串而不是一个json对象:

<select ng-model="selected">
    <option ng-repeat="item in items" value="{{item}}">
          {{item.name}} <span>Some nice data</span>
    </option>
</select>
Run Code Online (Sandbox Code Playgroud)

我怎么才能得到它?我必须为它创建一个指令吗?

这里我的代码在没有附加数据的情况下工作到选择框中

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

});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

Thi*_*gri 6

您无法从ngOptionsAngularJS指令输出HTML .但您可以使用函数来自定义选项内容以标记元素,如下所示(请注意HTML已转义):

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>';
  };
});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)