在Angular.js中附加到模型的复选框
checkboxes that append to a model in Angular.js
我有一个模型,它将与许多其他模型相关。想象一个堆栈溢出问题,例如,它是一个与标记相关的问题。在POST
或PUT
:之前,最后一个Object可能如下所示
{
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
})
}
基本上,它需要一个指令来实现你的目标看看我为你写的plunker。正如您所看到的,在所选标记的列表中,每个标记的text
属性都会显示出来,这意味着保留了对象结构。在您的情况下,您将绑定$scope.question.tags
数组作为collection
属性,并将$scope.tags
中的每个标记作为element
属性。
这里是绑定到同一模型的多个复选框的代码笔。
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++;
};
});
如果有人在查找这个问题,我发现了一个名为checklist模型的很棒的库,值得一提。我所要做的或多或少就是:
<div class="checkbox" ng-repeat="tag in tags">
<label>
<input type="checkbox" checklist-model="question.tags" checklist-value="tags"> {{ tag.name }}
</label>
</div>
在谷歌上搜索"角度复选框指令"时发现了这一点。
相关文章:
- 如何在Knockout.js中选中复选框时更新视图模型及其依赖项
- 当ng repeat上的复选框具有必需的属性时,角度ng模型将变为未定义
- 复选框仅在第二次单击后更新模型
- “角度形状”复选框最初未包含在模型中
- 在angularjs复选框输入中更新ng模型或执行ng更改之前需要确认
- AngularJS:单选复选框模型不会改变
- 在Angular.js中附加到模型的复选框
- AngularJs 将模型属性绑定到复选框
- 如何通过单击来自javascript外部的复选框来更新AngularJS模型
- 将 Model.ID 绑定到复选框列表,并将模型.X、模型.Y 等属性发布到控制器
- Jquery for 复选框不适用于模型弹出窗口
- 将 AngularJS 数据模型绑定到基础复选框
- AngularJS 复选框不更新模型
- AngularJS:初始复选框值不在模型中
- 如何使用AngularJS中的ng模型获取复选框值(由用户检查)
- Extjs使用复选框模型在网格上拖放单个项目
- 基于mvc模型设置html复选框复选值
- 动态添加复选框,而不是模型绑定到IList
- 将复选框的默认值绑定到角度模型,其中true和amp;false表示为'是'&'没有'
- 如何使用ng模型绑定动态复选框值