繁体   English   中英

使用自定义选项模板进行角度选择

[英]angular select with custom option template

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

问题是我需要在选择框中显示比对象名称更多的内容,我尝试过此操作,但它返回的是字符串而不是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> 

您无法从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> 

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM