【问题标题】:Ng-init in the selection for default value with AngularJS doesn't work使用 AngularJS 选择默认值时的 Ng-init 不起作用
【发布时间】:2016-06-14 08:05:03
【问题描述】:

在网络应用程序中,我有一个费用列表,如果您按下它,它会将您带到一个新页面以编辑选定的费用。当用户单击列表元素时,我将对象(选定的费用)保存在整个应用程序通用的全局对象中,并在编辑控制器中检索它:

$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

在一项费用中,只有一家公司。 所以,在这个编辑页面中,我有一些字段(输入类型文本、日期等)。我还有一个selection,其中包含已登录用户的公司列表。为了检索那个列表,我做了这个函数:

$scope.getCompanyList = function() {
    EditExpenseListSrv.getCompanyListDetail(user).then(function (companyListDetail) {
        $scope.companyList = companyListDetail;
        $scope.$apply();
    }).catch(function (err) {
        console.log(err);
    });
};

CompanyListDetail 是一个对象数组:

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

所以选择Expense的公司($scope.companySelected)肯定会是查询得到的列表的一部分($scope.companyList)。但我想给用户改变它的可能性。 所以我想创建一个包含列表($scope.companyList)的selection,并且默认已经选择了与$scope.companySelected相对应的公司。

我已经写了这个,但它不起作用:

<select class="selection" ng-model="companySelected"
                          ng-init="companySelected = globalApplicationData.selectedExpenseList" 
                          ng-options="company 
                          as company.data.name for company in companyList">

但它不起作用。我可以在选择中看到所有公司,但不要选择默认值

【问题讨论】:

  • 您需要在controller 中分配该值,而不是在ng-init 中进行分配。
  • 但我确实写了 $scope.companySelected = GlobalApplicationData.selectedExpenseList;

标签: javascript angularjs selection ng-options ng-init


【解决方案1】:

当您为select 分配默认值时,您需要分配对象,因此当分配与其他对象的相同数据时,它将不起作用:

注意:

a) data 是在 select 列表中循环的数组

b) selectedcountry 是绑定在select 列表上的模型。

选项 1:

使用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:

controller分配默认值

$scope.selectedcountry = $scope.data[0];

Demo 2

【讨论】:

    【解决方案2】:

    您可以尝试在控制器中进行初始化:

    $scope.companySelected = "the value that you want to set here"
    

    或者您可以尝试将 ng-init 放在 select 的父级中。一旦我遇到这样的问题,我解决了它,将 ng-init 放在父标签中。示例:

    <div id="parent" ng-init="companySelected = globalApplicationData.selectedExpenseList">
        <select ...>
    </div>
    

    另一个想法是将 companySelected 放在一个对象中。如果我在 ng-value 中使用 $scope.value 而不是使用 $scope.formData.value

    ,我的表单会出现一些问题(我不确定为什么)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-22
      • 1970-01-01
      • 2016-09-09
      • 2016-12-11
      • 1970-01-01
      • 1970-01-01
      • 2014-02-16
      • 1970-01-01
      相关资源
      最近更新 更多