我想要的是选择的变量对于每个范围应该是唯一的。
是的你可以。
多控制器方式
您可以为每个用户创建根控制器mainController
并将新控制器添加到您的模型中。users
之后,在 ng-repeat 中调用新控制器为ng-controller="user.ctrl"
演示Fiddle
我会写这样的东西:
HTML
<div ng-controller="mainController">
<table>
<tbody ng-repeat="user in users" ng-controller="user.ctrl" 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" style="padding-left: 10px">{{user.desc}}</td>
</tr>
</tbody>
</table>
</div>
JS
var fessmodule = angular.module('myModule', []);
fessmodule.controller('mainController', function ($scope) {
$scope.users = [{
ctrl: fooCtrlA,
name: "AAAAA",
email: "a2009@gmail.com",
desc: "Description about AAAA"
}, {
ctrl: fooCtrlB,
name: "BBBBB",
email: "b2009@gmail.com",
desc: "Description about BBBBB"
}, {
ctrl: fooCtrlC,
name: "CCCCC",
email: "c2009@gmail.com",
desc: "Description about CCCC"
}];
});
fessmodule.$inject = ['$scope'];
function fooCtrlA($scope) {
$scope.selected = true;
$scope.toggleSelectedUser = function () {
$scope.selected = !$scope.selected;
};
$scope.isSelectedUser = function () {
return $scope.selected;
};
}
function fooCtrlB($scope) {
$scope.selected = false;
$scope.toggleSelectedUser = function () {
$scope.selected = !$scope.selected;
};
$scope.isSelectedUser = function () {
return $scope.selected;
};
}
function fooCtrlC($scope) {
$scope.selected = false;
$scope.toggleSelectedUser = function () {
$scope.selected = !$scope.selected;
};
$scope.isSelectedUser = function () {
return $scope.selected;
};
}
但是你可以看到我们有重复的代码!!. 每个“子”控制器都有相同的逻辑:
$scope.selected = false;
$scope.toggleSelectedUser = function () {
$scope.selected = !$scope.selected;
};
$scope.isSelectedUser = function () {
return $scope.selected;
};
如果你想让你的代码工作,我会使用ng-model
.
ng-model 的其他方式
演示 2Fiddle
HTML
<tbody ng-repeat="user in users" ng-click="toggleSelectedUser(user)" ng-switch on="isSelectedUser(user)">
<tr ng-model="user">
<td>{{user.name}}</td>
<td>{{user.email}}</td>
</tr>
<tr ng-switch-when="true">
<td colspan="2" style="padding-left: 10px">{{user.desc}}</td>
</tr>
</tbody>
和带有修改模型的控制器:
var fessmodule = angular.module('myModule', []);
fessmodule.controller('mainController', function ($scope) {
$scope.users = [{
selected: false,
name: "AAAAA",
email: "a2009@gmail.com",
desc: "Description about AAAA"
}, {
selected: false,
name: "BBBBB",
email: "b2009@gmail.com",
desc: "Description about BBBBB"
}, {
selected: false,
name: "CCCCC",
email: "c2009@gmail.com",
desc: "Description about CCCC"
}];
$scope.toggleSelectedUser = function (user) {
user.selected = !user.selected;
};
$scope.isSelectedUser = function (user) {
return user.selected;
};
});