0

I have this array in my scope

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

Can I create something like this ng-options?

<option value="1">Icebox</option>
<option value="2">Summer</option>
<option value="3">Milestone</option>
1
  • It puts the index instead of v.id Commented Dec 9, 2013 at 12:22

4 Answers 4

5

You can use ng-options

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

Fiddle DEMO

Sign up to request clarification or add additional context in comments.

1 Comment

The OP says nothing about a tile attribute. He is only interested in how he can display the title from the object as label. So this is the correct answer. The "... as... for ... in ..." construction is the way to go.
4

Yes, if you are interested to show title use this way:

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

Demo Fiddle

But if you want only to show value ng-options will be enogh

3 Comments

Can't I do it with ng-options?
Works for me. But not an elegant solution.
but what about reading the value back and syncing with some scope model?
0

I ran in to this same issue, where I was required to use ng-options, this was my solution...

HTML:

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

Controller:

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

Comments

0

See this directive for showing title on options with ng-options.

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);
                });
            });
        }
    };
}

Use it like this

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

Hope it helps

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.