我正在尝试向select元素添加一个选项。该值由jquery ui模式中的用户表单给出。
当我使用Chrome Developer工具时,我可以看到绑定的对象数组确实正在获取新对象,但它没有出现在select元素中。
我在控制台中使用$('#company')。scope()。供应商来调出阵列。它显示了要添加到数组中的项目,但它们未显示在选择框中。
这就是我所拥有的:
app.js
app.factory('Vendors', function(){
var Vendors = {};
Vendors.list = [
{
id: 1,
name: 'Company 1'
},
{
id: 2,
name: 'Company 2'
},
{
id: 3,
name: 'Company 3'
}
]
return Vendors;
})
app.controller('companyCtrl', function($scope, Vendors){
$scope.vendors = Vendors;
$scope.selectedVendor = 0;
$scope.companySelect = function(){
alert("You chose " + $scope.selectedVendor.name)
}
$scope.addCompany = function(name){
var maxId = 0;
for(var i=0; i<$scope.vendors.list.length; i++){
maxId = $scope.vendors.list[i].id;
}
newVendor = {id:++maxId, name:name};
$scope.vendors.list.push(newVendor)
$scope.selectedVendor = newVendor;
}
})
HTML
<div class="row">
<div class="grid_12" ng-controller="companyCtrl" id="company">
<span>Company</span>
<select ng-model="selectedVendor" ng-change="companySelect()" ng-options="v.name for v in vendors.list">
<option value="">-- Choose Company --</option>
</select>
<small><button onclick="openModal('addCompany');">Add</button></small>
</div>
</div>
Inline JS
$( "#addCompany" ).dialog({
autoOpen: false,
width: 350,
modal: true,
buttons: {
"Create new company": function() {
var name = $('#name').val();
if(name != ''){
$('#company').scope().addCompany(name);
}
$( this ).dialog( "close" );
},
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
$('#name').val( "" );
}
});
function openModal(id){
$('#'+id).dialog('open');
}
我尝试创建一个jsFiddle,但我想我不太确定如何让所有东西在那里工作。但无论如何,这是我的尝试:http://jsfiddle.net/aPXxe/
答案 0 :(得分:1)
试试这个:
$scope.$apply(function(){
$scope.vendors.list.push(newVendor);
$scope.selectedVendor = newVendor;
});