AngularJS - 在同一控制器下使用ng-repeat两次

时间:2013-05-27 10:41:10

标签: angularjs

我有以下DIV:

<div ng-controller="userControl">
    <div ng-repeat="user in users">
        <u>{{user.id}} : {{user.name}}</u><br />
        <div ng-repeat="role in user.roles">
            {{role.name}}
        </div>
        <br />
    </div>
    <form ng-submit="addRoleToUser()">
        <select name="userSelect">
        <div ng-repeat="user in users">
                <option value="{{user.id}}">{{user.name}}</option>
        </div>
        </select>
        <input type="submit" value="add">
    </form>
</div>

这是我的控制者:

function userControl($scope,$http) {
    $scope.users = [
                        {"id":"0","name":"Username1","roles":[{}]},
                        {"id":"1","name":"Username2","roles":[{}]},
                    ]

    $scope.addUser = function() {
        var nextid = $scope.getNextId();
        $scope.users.push({id:nextid,name:$scope.userName});
        /*
        $.post({}); //Push changes to server
        */
        $scope.userName = '';
    };

    $scope.getNextId = function() {
        var count = 0;
        angular.forEach($scope.users, function(data) {
          count = data.id;
        });
        var count2 = parseInt(count)+1;
        return count2;
     };

}

我可以看到第一个ng-repeat工作正常并列出了user.iduser.name,但是第二个ng-repeat(表单中的一个)没有显示信息,是这与我之前在div中已经循环过该元素的事实有关吗?

1 个答案:

答案 0 :(得分:1)

你误用了select指令:

<select ng-model="selectedUser" name="userSelect" ng-options="user.id as user.name for user in users">

http://docs.angularjs.org/api/ng.directive:select