基于模型值的ng-repeat

时间:2015-11-27 18:11:38

标签: angularjs angularjs-ng-repeat ng-repeat

我试图根据我的模型的价值重复一段HTML。如果用户选择" 3"在下拉列表中,它将显示" 1,2,3"每个人都有自己的div。之后,如果用户将下拉列表更改为2,则它应仅呈现" 1,2"。

这是我尝试的内容:

<html ng-app="app">
    <head>
        <title>teste</title>
    </head>
    <body ng-controller='testController'>
        <select ng-model="quantity">
            <option value="1" selected="selected">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
        </select>

        <div ng-repeat="i in getNumber(quantity) track by $index">{{$index + 1}}</div>

        Value on Model:{{quantity}}

        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
        <script>
            var app = angular.module("app",[]);
            app.controller('testController',['$scope', function($scope){

                $scope.quantity = 1;

                $scope.getNumber = function (num) {
                    return new Array(num);
                };

            }]);
        </script>
    </body>
</html>

到目前为止,它还没有根据模型值处理渲染部分。我在想什么?

3 个答案:

答案 0 :(得分:2)

使用limitTo filter是最常用的方法

&#13;
&#13;
angular.module('app',[])
.controller('testController', function($scope) {
  $scope.values=[1,2,3,4,5,6];
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

    <body ng-app="app" ng-controller='testController'>
        <select ng-model="quantity">
            <option value="1" selected="selected">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
        </select>

        <div ng-repeat="i in values | limitTo:quantity">{{i}}</div>
      </body>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

$scope.getNumber = function (num) { return new Array(parseInt(num)); };

也适用于您的代码

答案 2 :(得分:-1)

<html ng-app="app">
    <head>
        <title>teste</title>
    </head>
    <body ng-controller='testController'>
        <select ng-model="quantity" ng-change="changed()">
            <option value="1" selected="selected">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
        </select>

        <div ng-repeat="i in values track by $index">{{$index + 1}}</div>

        Value on Model:{{quantity}}

        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
        <script>
            var app = angular.module("app",[]);
            app.controller('testController',['$scope', function($scope){

                $scope.quantity = 1;
                $scope.values = [1]

                $scope.getNumber = function (num) {
                    return new Array(num);
                };

                $scope.changed = function() {
                  $scope.values = new Array(parseInt($scope.quantity));
                }

            }]);
        </script>
    </body>
</html>