在网络应用程序中,我有一个费用列表,如果您按上面的按钮,您将进入一个新页面来编辑选定的费用。当用户单击列表的元素时,我将对象(选定的费用)保存在整个应用程序中通用的全局对象中,并在编辑 Controller 中检索它:
$scope.companySelected = GlobalApplicationData.selectedExpenseList;
GlobalApplicationData.selectedExpenseList 是一个对象:
$$hashKey: "object:39"
_id: "33aa5549-7802-40d9-bc89-8780705b8c9b"
_rev: "3-eb940cb990524112723f711618e0cf51"
ad_table_id: 1000596
company_name: "Company 1"
data: Object
recordid: 1000005
__proto__: Object
一项支出中只有一家公司。
因此,在这个编辑页面中,我有一些字段(输入类型文本、日期等)。我还有一个选择
,其中包含登录用户的公司列表。为了检索该列表,我创建了以下函数:
$scope.getCompanyList = function() {
EditExpenseListSrv.getCompanyListDetail(user).then(function (companyListDetail) {
$scope.companyList = companyListDetail;
$scope.$apply();
}).catch(function (err) {
console.log(err);
});
};
CompanyListDetail 是一个 Obejct 数组:
companyListDetail: Array[5]
0: Object
1: Object
2: Object
3: Object
4: Object
这是这些对象的一个示例:
_id: "44e620dc-e715-453f-882b-3f21aeef48fe"
_rev: "1-c09c9f3350e853e588f3358aaafc0374"
ad_table_id: 1000146
data: {
description: "text"
id_company: 513424
name: "Company 2"
}
recordid: 1000002
因此,所选费用的公司 ($scope.companySelected
) 肯定会成为查询获取的列表 ($scope.companyList
) 的一部分。但我想给用户改变它的可能性。
所以我想进行一个包含列表($scope.companyList
)的选择
,并且默认已经选择了与$scope.companySelected
对应的公司.
我已经写了这个,但它不起作用:
<select class="selection" ng-model="companySelected"
ng-init="companySelected = globalApplicationData.selectedExpenseList"
ng-options="company
as company.data.name for company in companyList">
但是这不起作用。我可以在选择中看到所有公司,但不要选择默认值
最佳答案
当您为select
分配默认值时,您需要分配对象,因此当分配其他对象的相同数据时,它将不起作用:
注意:
a) data
是在 select
列表中循环的数组
b) selectedcountry
是绑定(bind)在select
列表上的模型。
选项 1:
Using
ng-init
:
<select ng-model="selectedcountry" ng-init="selectedcountry = data[0]" ng-options="item.name for item in data">
<option value="">Select</option>
</select>
Demo 1 。
选项 2:
Assigning the default from the
controller
$scope.selectedcountry = $scope.data[0];
关于javascript - AngularJS 选择默认值时的 ng-init 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37806328/