在同一个DOM元素上的angularjs-ng-repeat和ng-controller

前端之家收集整理的这篇文章主要介绍了在同一个DOM元素上的angularjs-ng-repeat和ng-controller前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我们可以将ng-controller和ng-repeat附加到同一个DOM元素吗?
Fiddle

这是HTML:

<table>
    <tbody ng-controller="UserController" ng-repeat="user in users" ng-click="toggleSelectedUser()" ng-switch on="isSelectedUser()">
        <tr>
            <td>{{user.name}}</td>
            <td>{{user.email}}</td>
        </tr>
        <tr ng-switch-when="true">
            <td colspan="2">
                {{user.desc}}
            </td>
        </tr>
    </tbody>
</table>

这是代码

angular.module("myApp",[])     
    .controller("UserController",["$scope",function($scope) {
        $scope.users = [
            {name : "Anup Vasudeva",email : "anup.vasudeva2009@gmail.com",desc : "Description about Anup Vasudeva"},{name : "Amit Vasudeva",email : "amit.vasudeva2009@gmail.com",desc : "Description about Amit Vasudeva"},{name : "Vijay Kumar",email : "vijay.kumar@gmail.com",desc : "Description about Vijay Kumar"}
        ];
        $scope.selected = false;

        $scope.toggleSelectedUser = function() {
            $scope.selected = !$scope.selected;
        };

        $scope.isSelectedUser = function() {
            return $scope.selected;
        };
    }]);

我认为将ng-controller和ng-repeat绑定到同一个DOM元素是有意义的.由ng-repeat创建的范围可由控制器管理.我想要的是所选择的变量对于每个范围应该是唯一的.

解决方法

你应该把你的控制器分成UserListController和UserController.用户列表应该是UserListController的一部分,每个项目都可以由UserController管理

就像是

<table ng-controller='UserListController'>
        <tbody ng-controller="UserController" ng-repeat="user in users" ng-click="toggleSelectedUser()" ng-switch on="isSelectedUser()" ng-init="user=user">

所以用户控制器变成了

angular.module("myApp",function($scope) {
        $scope.selected = false;

        $scope.toggleSelectedUser = function() {
            $scope.user.selected = !$scope.selected;
        };

        $scope.isSelectedUser = function() {
            return $scope.user.selected;
        };
    }]);

猜你在找的HTML相关文章