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
168 views
in Technique[技术] by (71.8m points)

AngularJS ng-options create range

I am trying to create a select element that has a list of numbers 1 to pages where pages is a variable that is the number of pages I have. What i don't know how to do is to structure the ng-options expression so that it will give me the numbers I need. Here is what I have so far

<select ng-model="page" ng-options="???"></select>

what do I need to put in the ng-options expression in order for it to create my select like

<select>
    <option value="1">1</option>
    ...
    <option value="35">35</option>
</select>

do I need to create a function that returns an array of numbers and use it in there somehow or is there an easier way to do this?

any help would be greatly appreciated.

Thanks

EDIT

After posting my question i figured out one way to do it by creating a function called Range in my controller that takes two numbers and returns an array with all the values in that range.

$scope.Range = function(start, end) {
    var result = [];
    for (var i = start; i <= end; i++) {
        result.push(i);
    }
    return result;
};

then in the HTML I did

<select ng-name="page" ng-options="page for page in Range(1, pages)"></select> 

Is this the simplest way to do this or is there a better way?

question from:https://stackoverflow.com/questions/11160513/angularjs-ng-options-create-range

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

1 Reply

0 votes
by (71.8m points)

Your way works fine. Another option that came to my head is to use a filter, so you don't have to pollute your controller with Range.

JS:

var myApp = angular.module('myApp', []);
myApp.filter('range', function() {
  return function(input, min, max) {
    min = parseInt(min); //Make string input int
    max = parseInt(max);
    for (var i=min; i<max; i++)
      input.push(i);
    return input;
  };
});

HTML:

<select ng-model="page" ng-options="n for n in [] | range:1:30"></select>

Example: http://jsfiddle.net/N3ZVp/1/

P.S. in your example in your main post, you didn't put var in front of i. So i is declared as a global variable in your example.


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

...