Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-repeat and ng-controller on the same DOM element

Can we attach ng-controller and ng-repeat to the same DOM element? Fiddle

Here is the 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>

Here is the code:

angular.module("myApp", [])     
    .controller("UserController", ["$scope", function($scope) {
        $scope.users = [
            {name : "Anup Vasudeva", email : "[email protected]", desc : "Description about Anup Vasudeva"},
            {name : "Amit Vasudeva", email : "[email protected]", desc : "Description about Amit Vasudeva"},
            {name : "Vijay Kumar", email : "[email protected]", desc : "Description about Vijay Kumar"}
        ];
        $scope.selected = false;

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

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

I think it makes sense to bind ng-controller and ng-repeat to the same DOM element. The scope created by ng-repeat can be managed by the controller. What I want is the variable selected should be unique for each scope.

like image 697
Anup Vasudeva Avatar asked Oct 25 '13 11:10

Anup Vasudeva


1 Answers

You should break your controller into UserListController and UserController. The list of users should be part of UserListController and the each item can be managed by UserController

Something like

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

So the user controller becomes

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

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

        $scope.isSelectedUser = function() {
            return $scope.user.selected;
        };
    }]);
like image 91
Chandermani Avatar answered Oct 12 '22 15:10

Chandermani