我有一个表单,可以像这样更新提交的值
<form ng-submit="updateMovie()">
<input type="text" ng-model="movie.title"/>
<input type="text" ng-model="movie.rating"/>
//what to attach here at ng-model//
<input type="text" ng-modal ="movie.__"/>
there could be many genre inputs based on how many user wants to input
</form>
表单提交的对象将是以下类型。暂时让 忽略ID 。我不知道我怎么能创造这种类型 即 对象数组
"id": 4792,
"title": "Insidious",
"rating": "7.0",
"genres": [
{
"id": 3,
"name": "horror"
},
{
"id": 7,
"name": "Drama"
}
]
答案 0 :(得分:1)
您可以将用户输入的所有内容添加到列表(movie.genres
)中,然后单击按钮。
所以你可以这样:
angular.module("app", [])
.controller('mainCtrl', function($scope) {
$scope.movie = {};
$scope.movie.genres = [];
$scope.add = function() {
if ($scope.genre) {
$scope.movie.genres.push($scope.genre);
$scope.genre = '';
}
}
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>
<body ng-controller="mainCtrl">
<form ng-submit="updateMovie()">
<label for="title">Title: </label>
<input type="text" id="title" ng-model="movie.title">
<br>
<label for="rating">Rating: </label>
<input type="text" id="rating" ng-model="movie.rating">
<br>
<label for="genre">Genre: </label>
<input type="text" id="genre" ng-model="genre">
<button type="button" ng-click="add()">Add genre</button>
</form>
</body>
</html>
答案 1 :(得分:0)
首先,您尝试允许用户输入 任何 ,然后将该潜在随机输入与预定义的数据集进行匹配,从而产生固有的设计缺陷。我强烈推荐一种替代方法,例如多选下拉列表或复选框。即使是将用户限制为预定义类型集的自动建议功能也会有巨大的改进。
那就是说,如果你想继续这种方法,你可以采取正确的方向。
将表格数据中输入的类型的ng-model
解耦。这意味着在updateMovie()
中,您将根据需要转换数据。
允许用户将流派绑定到一个简单的字符串:
<input type="text" ng-model ="movie.userGenres"/>
在updateMovie()
方法中,根据空格,逗号等划分数据,并在可能的情况下将其映射到您的流派数组,并发布该映射数据而不是用户输入的字符串。
答案 2 :(得分:-1)
您可以使用ngTagInput。
var app = angular.module('app', []);
app.controller('yourCtrl', function() {
$scope.movie = {
name: '',
description: '',
genre: [],
};
});
<tags-input id="genre" class="input-border" ng-model="movie.genre"
placeholder="Genere for movie"
add-on-comma="true"
replace-spaces-with-dashes="false"
on-tag-added="$tag.text=$tag.text.toLowerCase()"></tags-input>
您需要将流派转换为所需的格式,因为它类似于以下数组:
[{text: 'genre1'}, {text: 'genre2'}]
答案 3 :(得分:-1)
你应该使用有角度的ui-select(https://github.com/angular-ui/ui-select) 这可用于选择多个值。 这里也是示例http://angular-ui.github.io/ui-select/demo-multiple-selection.html
您还可以实现on刷新功能,该功能将返回可用流派列表+输入的流派 https://github.com/angular-ui/ui-select/wiki/ui-select-choices