关于ng-repeat,我们可以在ng-repeat语句中绑定

时间:2016-12-22 12:08:41

标签: angularjs

<!DOCTYPE html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    </head>
    <body>
        <div ng-app="myApp" ng-controller="customersCtrl"> 
            <button ng-click="call('d')">for d</button>
            <button ng-click="call('f')">for f</button>
            <ul>
                <li ng-repeat="x in a.{{replace}}">
                    {{x}}
                </li>
            </ul>
        </div>
        <script>
            var app = angular.module('myApp', []);
            app.controller('customersCtrl', function($scope) {
                $scope.a = {
                    d:[1,2,3,4,5],
                    f:[6,7,8,9]
                };
                $scope.call = function(val) {
                    $scope.replace='val';
                }
            });
        </script>
    </body>
</html>

我正在尝试动态地将值添加到ng-repeat内容中,但它不起作用,请帮忙 我们可以动态地为ng-repeat本身添加值,这样我们就可以通过简单地改变上面的一个值来改变迭代值,如果没有更好的想法那么

2 个答案:

答案 0 :(得分:3)

以下代码段可以为您提供帮助。

&#13;
&#13;
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">
</script>

<body>

    <div ng-app="myApp" ng-controller="customersCtrl">
        <button ng-click="call('d')">for d</button>
        <button ng-click="call('f')">for f</button>
        <ul>
            <li ng-repeat="x in a[replace]">
                {{x}}
            </li>
        </ul>

    </div>

    <script>
        var app = angular.module('myApp', []);
        app.controller('customersCtrl', function ($scope) {
            $scope.a = {
                d: [1, 2, 3, 4, 5],
                f: [6, 7, 8, 9]
            }
            $scope.call = function (val) {
                $scope.replace = val;
            }
        });
    </script>

</body>

</html>
&#13;
&#13;
&#13;

说明:

$scope.replace=val; //Assign the variable and not a string

<li ng-repeat="x in a[replace]"> // No need to use braces are you are in an ng tag already

答案 1 :(得分:1)

您可以传递调用函数中的值,而不是传递字符串,然后将这些值分配给$ scope.replace,然后更新您的ng-repeat

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">       </script>
    <body>

        <div ng-app="myApp" ng-controller="customersCtrl"> 
            <button ng-click="call(a.d)">for d</button>
            <button ng-click="call(a.f)">for f</button>
            <ul>
                <li ng-repeat="x in replace">
                    {{x}}
                </li>
            </ul>
        </div>

        <script>
            var app = angular.module('myApp', []);
            app.controller('customersCtrl', function($scope) {
                $scope.a = {
                   d: [1,2,3,4,5],
                   f: [6,7,8,9]
                }
                $scope.call = function(val){
                    $scope.replace=val;}
                }
            );
        </script>

    </body>
</html>