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

时间:2014-11-26 19:39:33

标签: javascript angularjs select

我有一个选择显示对象列表,一个按钮显示对象选择的数据。有用。

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

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

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

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

&#13;
&#13;
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);
  }

});
&#13;
<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>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:6)

您无法从ngOptions AngularJS指令输出HTML。 但是你可以使用一个函数来自定义选项内容来标记元素,就像这样(注意HTML被转义):

&#13;
&#13;
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>';
  };
});
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

将HTML放在选项的选项标记内无效。您只需要使用DIV标签或任何适合您需求的标签来创建您自己的标签。另外请注意,您可能需要重新考虑您的UI,因为下拉的目的不是浏览数据