我正在使用角度js制作应用程序。它是这样的。
用户创建群组并添加群组名称
用户创建“网站”,每个网站都可以查看上一步创建的群组
问题是当他只检查一个复选框时,会检查所有组复选框。
以下是生成复选框的代码:
<p>Groups:
<label ng-repeat='group in groups'>
<input type="checkbox" ng-model="newSite.groups" name="group-check" value="{{group.id}}"/>
{{group.name}}</label></p>
以下是输出的代码:
<label ng-repeat="group in groups" class="ng-scope ng-binding">
<input type="checkbox" ng-model="newSite.groups" name="group-check" value="0" class="ng-valid ng-dirty">
first group</label>
<label ng-repeat="group in groups" class="ng-scope ng-binding">
<input type="checkbox" ng-model="newSite.groups" name="group-check" value="1" class="ng-pristine ng-valid">
second group</label>
谢谢!
编辑:这是plunker链接http://beta.plnkr.co/edit/OVBoTDY2YmXgSy8TAbIW
答案 0 :(得分:5)
This (plunker)就是这样做的。我们的想法是创建一个模型来跟踪已检查的组。
<强> JS 强>
app.controller("WebsitesCtrl", function($scope) {
$scope.newSite = {};
$scope.newGroup = {};
$scope.checkedGroupIds = {};
$scope.sites = [];
var groupMap = {};
$scope.groups = [];
var siteIdSeq = 0;
function createSite(newSite, groups) {
$scope.sites.push(newSite);
newSite.id = siteIdSeq;
newSite.groups = groups;
siteIdSeq++;
return newSite;
}
var groupIdSeq = 0;
function createGroup(newGroup) {
$scope.groups.push(newGroup);
newGroup.id = groupIdSeq;
groupMap[newGroup.id] = newGroup;
groupIdSeq++;
return newGroup;
}
$scope.submitSite = function() {
var groups = [];
angular.forEach($scope.checkedGroupIds, function(checked, id) {
if(checked) {
groups.push(groupMap[id]);
}
});
createSite($scope.newSite, groups);
$scope.newSite = {};
$scope.checkedGroupIds = {};
};
$scope.submitGroup = function() {
createGroup($scope.newGroup);
$scope.newGroup = {};
};
//test data
$scope.newSite.url = 'http://www.my-site.com';
var all = createGroup({name:'All'});
var home = createGroup({name:'Home'});
var fav = createGroup({name:'Fav'});
createSite({url:'http://www.stackoverflow.com'}, [all, fav]);
createSite({url:'http://www.google.com'}, [fav]);
createSite({url:'http://www.plnkr.co'}, [home]);
});
<强> HTML 强>
<div id="website-form">
Sites:
<ul>
<li ng-repeat="site in sites">{{site}}</li>
</ul>
<form ng-submit="submitSite()">
<label>Site url: <input type="url" ng-model="newSite.url" /></label>
<p>Groups:
<label ng-repeat='group in groups'>
<input type="checkbox" name="group-check" value="{{group.name}}" id="{{group.id}}"
ng-model="checkedGroupIds[group.id]" />
{{group.name}}
</label>
</p>
<input type="submit" id="submitWebsite" value="Save Changes" ng-disabled="!newSite.url" />
</form><!-- end submitSite() -->
</div>
<div id="group-form">
<form ng-submit="submitGroup()">
<label>Name of the group: <input ng-model="newGroup.name" /></label>
<input type="submit" class="btn btn-primary" id="submitGroup" value="Save Changes"
ng-disabled="!newGroup.name"/>
</form><!-- end submitGroup() -->
</div>