AngularJS For Loop with Numbers & Ranges

后端 未结 24 3455
抹茶落季
抹茶落季 2020-11-22 13:40

Angular does provide some support for a for loop using numbers within its HTML directives:

do something <
24条回答
  •  清歌不尽
    2020-11-22 14:41

    I came up with a slightly different syntax which suits me a little bit more and adds an optional lower bound as well:

    myApp.filter('makeRange', function() {
            return function(input) {
                var lowBound, highBound;
                switch (input.length) {
                case 1:
                    lowBound = 0;
                    highBound = parseInt(input[0]) - 1;
                    break;
                case 2:
                    lowBound = parseInt(input[0]);
                    highBound = parseInt(input[1]);
                    break;
                default:
                    return input;
                }
                var result = [];
                for (var i = lowBound; i <= highBound; i++)
                    result.push(i);
                return result;
            };
        });
    

    which you can use as

    Do something 0..9: {{n}}

    or

    Do something 20..29: {{n}}

提交回复
热议问题