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

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

问题描述

我正在尝试创建一个 select 元素,其中包含一个数字 1 到页面的列表,其中 pages 是一个变量,即我拥有的页面数.我不知道该怎么做是构造 ng-options 表达式,以便它给我我需要的数字.这是我目前所拥有的

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-options 表达式中放入什么才能创建我的选择

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?

任何帮助将不胜感激.

谢谢

编辑

发布我的问题后,我想出了一种方法,即在我的控制器中创建一个名为 Range 的函数,该函数接受两个数字并返回一个包含该范围内所有值的数组.

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?

推荐答案

你的方法很好.我想到的另一个选择是使用过滤器,这样您就不必用 Range 污染您的控制器.

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/

附言在您的主要帖子中的示例中,您没有将 var 放在 i 前面.所以 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-options 创建范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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