【问题标题】:angular select with custom option template带有自定义选项模板的角度选择
【发布时间】:2015-01-25 06:38:53
【问题描述】:

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

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

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

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

这是我的代码,无需在选择框中添加其他数据即可使用

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>

【问题讨论】:

    标签: javascript angularjs select


    【解决方案1】:

    将 HTML 放在选项标记中以进行选择是无效的。您只需要使用 DIV 标签或任何适合您需要的标签创建自己的标签。另一方面,您可能需要重新考虑您的 UI,因为下拉菜单的目的不是浏览数据

    【讨论】:

      【解决方案2】:

      您不能从 ngOptions AngularJS 指令输出 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>';
        };
      });
      <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>

      【讨论】:

      • 可以添加一个 ng-bind-html 或带有 $sce 的东西?
      • 不,该指令使用jQuery的text函数渲染option内容,并且没有选项使它使用html函数。查看来源:github.com/angular/angular.js/blob/master/src/ng/directive/…
      • 不幸的是,这似乎不适用于 Angular 1.5。原始 HTML 打印在 select 中。
      猜你喜欢
      • 2020-02-29
      • 2018-02-12
      • 1970-01-01
      • 2014-07-22
      • 2012-10-19
      • 2020-05-13
      • 2016-06-23
      • 2018-03-07
      • 2014-12-25
      相关资源
      最近更新 更多