我有一个模型,它将与许多其他模型相关。想想堆栈溢出问题,例如,它是与标签相关的问题。在POST
或PUT
:
{
id: 28329332,
title: "checkboxes that append to a model in Angular.js",
tags: [{
id: 5678,
name: "angularjs"
}, {
id: 890,
name: "JavaScript"
}]
}
到目前为止,我有以下控制器:
.controller('CreateQuestionCtrl',
function($scope, $location, Question, Tag) {
$scope.question = new Question();
$scope.page = 1;
$scope.getTags = function() {
Tag.query({ page: $scope.page }, function(data) {
$scope.tags = data;
}, function(err) {
// to do, error when they try to use a page that doesn't exist
})
};
$scope.create = function() {
$scope.question.$save(function(data) {
$location.path("/question/" + data.id);
});
};
$scope.$watch($scope.page, $scope.getTags);
}
)
所以我在页面上显示所有标记,分页。我希望他们能够选择给定的标签并将其附加到我的模型中,以便保存它。
如何创建一个复选框界面,使用所选的其他模型更新$scope.question
?
编辑:想想我可能会成为那里的一部分
<div class="checkbox" ng-repeat="tag in tags.objects">
<label><input
type="checkbox"
ng-change="setTag(tag.id)"
ng-model="tag"
> {{ tag.name }}
</div>
然后在控制器上
$scope.setTag = function(id) {
Tag.get({id: id}, function(data) {
// don't know what now
})
}
答案 0 :(得分:1)
基本上,它需要一个指令才能达到你的目标Take a look at the plunker I wrote for you。如您所见,在所选标记列表中显示每个标记的text
属性,这意味着保留了对象结构。在您的情况下,您可以将$scope.question.tags
数组绑定为collection
属性,将$scope.tags
中的每个标记绑定为element
属性。
答案 1 :(得分:0)
这里有一个codepen,用于绑定到同一模型的多个复选框。
HTML
<html ng-app="codePen" >
<head>
<meta charset="utf-8">
<title>AngularJS Multiple Checkboxes</title>
</head>
<body>
<div ng:controller="MainCtrl">
<label ng-repeat="tag in model.tags">
<input type="checkbox" ng-model="tag.enabled" ng-change="onChecked()"> {{tag.name}}
</label>
<p>tags: {{model.tags}}</p>
<p> checkCount: {{counter}} </p>
</body>
</html>
JS
var app = angular.module('codePen', []);
app.controller('MainCtrl', function($scope){
$scope.model = { id: 28329332,
title: "checkboxes that append to a model in Angular.js",
tags: [{
id: 5678,
name: "angularjs",
enabled: false
}, {
id: 890,
name: "JavaScript",
enabled: true
}]
};
$scope.counter = 0;
$scope.onChecked = function (){
$scope.counter++;
};
});
答案 2 :(得分:0)
如果有人正在查找这个问题,我发现great library called checklist-model值得一提。我所要做的只是或多或少:
<div class="checkbox" ng-repeat="tag in tags">
<label>
<input type="checkbox" checklist-model="question.tags" checklist-value="tags"> {{ tag.name }}
</label>
</div>
在谷歌搜索“角度复选框指令”中找到了这个。