Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
409 views
in Technique[技术] by (71.8m points)

javascript - Add two extra options to a select list with ngOptions on it

I have a bunch of select lists and I'm trying to add a "none" and a title option to them. The code looks like so:

<select ng-options="value.name for value in values" ng-model="selection">
    <option value="" disabled>{{title}}</option>
    <option value="">None</option>
</select>

For right now, I cannot add them to the data so I am trying to find a way to get this working. When I load them for the first time, the "none" option is not there. The title is there and works as intended, but it seems I cannot add two blank entries to this select list.

The easiest way would be to have the "none" option added to the data but it's not a possibility for me. Is there a proper way to achieve what I want?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

That's correct, you can only have one hard-coded element. <option ng-repeat> can technically be done, but that method only cleanly supports binding to strings, so it would get very kludgey to bind to objects, as you're doing.

You say you can't add "None" to the data, but you can do the next best thing: prepend it to the array ng-options is iterating across, using a filter:

app.filter('addNone', function () {
    return function(input) {
        var newArray = input.slice(0); //clone the array, or you'll end up with a new "None" option added to your "values" array on every digest cycle.
        newArray.unshift({ name: "None" });
        return newArray;
    };
})

Then use the filter like this:

 <select class="form-control" ng-options="value.name as value.name for value in filter.values | addNone" ng-model="filter.selected" ng-change="goSearch()">
                    <option value="" disabled>{{filter.name}}</option>
                </select>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...