gpt4 book ai didi

javascript - 带有自定义选项模板的 Angular 选择

转载 作者:行者123 更新时间:2023-12-03 16:42:36 25 4
gpt4 key购买 nike

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

问题是我需要在选择框中显示的不仅仅是对象名称,我试过这个但是它返回一个字符串而不是一个 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>

关于javascript - 带有自定义选项模板的 Angular 选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27157554/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com