ng-repeat 和 ng-controller 在同一个 DOM 元素上 [英] ng-repeat and ng-controller on the same DOM element
问题描述
我们可以将 ng-controller 和 ng-repeat 附加到同一个 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>
代码如下:
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 创建的范围可以由控制器管理.我想要的是变量 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.
推荐答案
你应该把你的控制器分成 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">
所以用户控制器变成了
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-repeat 和 ng-controller 在同一个 DOM 元素上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!