AngularJS ng选项与对象属性值&标题

AngularJS ng-options with object attributes value & title

本文关键字:amp 标题 属性 ng 选项 对象 AngularJS      更新时间:2024-05-23

我的作用域中有这个数组

$scope.containers = [{id: 1, title: "Icebox"}, {id: 2, title: "Summer"}, 
{id: 3, title: "Milestone"}];

我可以创建这样的ng选项吗?

<option value="1">Icebox</option>
<option value="2">Summer</option>
<option value="3">Milestone</option>

您可以使用ng-options

<select ng-options="v.id as v.title for v in containers" ng-model="selectedId">        
</select>

Fiddle DEMO

是的,如果您有兴趣显示标题,请使用以下方式:

<select>
    <option
    ng-repeat="v in containers" 
    value="{{v.id}}" 
    title="{{v.title}}" 
    ng-selected="adresses.indexOf(v) == 0">{{v.title}}
    </option>
</select>

演示Fiddle

但如果您只想显示value ng-options将是高

我遇到了同样的问题,要求我使用ng选项,这是我的解决方案。。。

HTML:

<select ng-options="item.Id as item.Name for item in vm.listOfItems">
    <option disabled>Select a value</option>
</select>

控制器:

vm.$onInit = function () {
    $timeout(function () {
         $("option").each(function (index, element) {
            var text = $(element).text();
            $(element).attr("title", text);
         });
    });
}

有关显示ng选项的标题,请参阅此指令。

angular.module("showTitle")
    .directive("showSelectTitle", ["$injector", showSelectTitle]);
function showSelectTitle($injector) {
    var $timeout = $injector.get("$timeout");
    return {
        scope: {},
        link: function (scope, element) {
            $timeout(function () {
                $(element).find("option").each(function (index, elem) {
                    elem = $(elem);
                    var text = elem.text();
                    var truncated = text.substring(0, 30) + "...";
                    elem.attr("title", text);
                    elem.text(truncated);
                    elem.attr("label", truncated);
                });
            });
        }
    };
}

像这样使用

<select show-select-title ng-model="yourModel.Value" ng-options="value as label for yourArrayOfObjects"></select>

希望它能帮助