AngularJS NG选项创建范围 [英] AngularJS ng-options create range

查看:85
本文介绍了AngularJS NG选项创建范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个具有数字1至页面列表,网页是一个变量,它是我的页数select元素。我不知道该怎么做是组织的NG选项前pression,这样就会给我,我需要的数字。以下是我迄今为止

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>

我需要什么就摆在NG选项前pression,以便它创建我的选择像

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?

任何帮助将大大AP preciated。

any help would be greatly appreciated.

感谢

修改

发布我的问题后,我想通了,通过创建一个在我的控制器,它有两个数字并返回与该范围内的所有值的数组称为范围功能做到这一点的方法之一。

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

然后在HTML我做

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?

再次感谢。

推荐答案

您的方式工作正常。那来到我的头另一种方法是使用过滤器,所以你不必与污染范围控制器。

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>

例如: http://jsfiddle.net/N3ZVp/1/

P.S。在你的主帖你的榜样,你没有把 VAR 前面我。因此, I 被声明为您的示例中的全局变量。

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.

这篇关于AngularJS NG选项创建范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆