【发布时间】:2016-01-15 11:39:54
【问题描述】:
在 select 中创建一个空白选项可能非常烦人。任何解决方案:
angular.module('myApp', ['ui.bootstrap','angularSpinners'])
.controller("StudentController",function($scope,$http,$modal){
$scope.students=[
{"first_name":"Miguel","last_name":"Smith","id":10},
{"first_name":"Ann","last_name":"Jones","id":11}
];
$scope.courselist=[
{"first_name":"Dave","last_name":"Smith","id":8},
{"first_name":"Mike","last_name":"Winner","id":9}
];
$scope.sDefault=$scope.courselist[0].id;
})
.directive('thisView', function() {
return {
restrict:"E",
scope: {
students:"=",
courselist:"=",
sDefault:"="
},
templateUrl: 'this-view.html',
controller: function($scope) {
$scope.remStudent = function(remId) {
$scope.students.splice( $.inArray(remId, $scope.students), 1 );
$scope.courselist.push(data);//data will be returned from http not relevant for question
};
$scope.addStudent = function(addId) {//this from student list
$scope.students.push(data);//data will be returned from http not relevant for question
$scope.courselist.splice( $.inArray(addId, $scope.courselist), 1 );
};
}
});
在主页上:
<div ng-controller="StudentController">
{{sDefault}} //works
<this-view students="students" courselist="courselist" sDefault="sDefault"></this-view>
</div>
this-view.html:
{{sDefault}} //doesn't work
<form ng-submit="addStudent(addStudentId)">
<select class="form-control" ng-model="addStudentId" >
<option value="" selected>Default</option>
<option ng-repeat="option in courselist" value="{{option.id}}" >{{option.first_name}} {{option.last_name}}</option>
</select>
<input type="submit" class="btn btn-primary btn-lg" value="Add Student" />
</form>
我尝试了一个没有空白选项的选择,但是当我这样做时,模型不会在提交时发布,所以我添加了一个默认值:
<option value="" selected>Default</option>
但是当我提交表单时,选择数组(课程列表)被拼接并添加了一个空白选项以及上面的默认选项和剩余的课程列表。
有没有办法从 courselist 数组中添加选项(没有角空白)并且仍然能够发布它。
我尝试发送默认值 - “sDefault”,但由于某种原因,它没有传递到指令中。
基本上我不需要默认选择,并且能够发布到表单,您认为简单吗?! ng-options 是一个问题,因为它不是单个项目输出,即 {{first_name}} {{last_name}} 并且无论如何都不会发布。
任何帮助表示赞赏。
更多信息:
感谢下面的 Timcodes,我找到了问题的原因,但仍然没有解决方案。 Example working without $http
我给出的上述代码是为了避免大量使用 $http。但我注意到使用带有 api 的真实版本会创建空白选择:
.controller("StudentController",function($scope,$http,$modal){
$scope.studentlist = function() {
$http.get('/api').
success(function(data) {
$scope.courselist = data;
});
};
$scope.studentlist();
});
$scope.courselist 输出 [{"first_name":"Miguel","last_name":"Smith","id":10}]
如果我把它直接放入控制器中:
$scope.courselist=[{"first_name":"Miguel","last_name":"Smith","id":10}]
它可以工作,就像在 plunker 示例中一样,但是使用 $http 它会创建一个空白的第一个选择选项。
解决方案:我决定将课程列表从后端预加载到 javascript 变量中,而不是 api 中。这样列表是在创建 selectedItem 之前定义的。
不过,我很想听听角度解决方案。
【问题讨论】:
标签: javascript angularjs forms select