NG-重复和NG-控制器相同的DOM元素 [英] ng-repeat and ng-controller on the same DOM element
问题描述
我们能重视NG-控制器和NG-重复相同的DOM元素?
小提琴
Can we attach ng-controller and ng-repeat to the same DOM element? 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>
下面是code:
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-控制器
和 NG-重复
相同的DOM元素。通过纳克重复创建的范围可以由控制器进行管理。我要的是选择的变量
应该是每个范围是独一无二的。
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.
推荐答案
您应该打破你的控制器到 UserListController
和 UserController的
。用户列表应UserListController的一部分,并且每个项目可以通过 UserController的
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
像
<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;
};
}]);
这篇关于NG-重复和NG-控制器相同的DOM元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!