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

前端 未结 2 1155
死守一世寂寞
死守一世寂寞 2020-12-20 17:39

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:


                        
    
提交评论

  • 2020-12-20 18:22

    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>
    
    0 讨论(0)
  • 提交回复
    热议问题