簡體   English   中英

角度選擇默認為第一個選項

[英]angular select default to first option

我似乎無法將下拉菜單默認為選擇第一家商店。

的HTML:

<select 
      id="store" 
      class="form-control input-inline input-medium"
      ng-model="orderVm.Stores.selectedStore.id">
    <option 
         ng-repeat="store in orderVm.Stores" 
         value="{{store.Id}}">
        {{store.MarketplaceName}}
    </option>
</select>
{{orderVm.Stores.selectedStore}}

vm.Stores(從本地JSON文件加載):

[
  {
    "Id": 1,
    "MarketplaceId": 1,
    "MarketplaceName": "Etsy"
    ]
  },
  {
    "Id": 2,
    "MarketplaceId": 2,
    "MarketplaceName": "Shopify"
  }
]

控制器:

angular
    .module('WizmoApp')
    .controller('orderController', orderController);

orderController.$inject = ['$http', '$location', 'toastr', 'DTColumnDefBuilder', 'DTOptionsBuilder', 'Cart', 'OrderService', 'PackageService'];

function orderController($http, $location, toastr, DTColumnDefBuilder, DTOptionsBuilder, Cart, OrderService, PackageService) {
        var vm = this;
        vm.Stores = json; //from file 
        vm.Stores.selectedStore = {
            id: vm.Stores[0].Id, 
            name: vm.Stores[0].MarketplaceName 
        };

        OrderService.getOrdersGroupedByStore(function (json) {
            vm.Stores = json;
            vm.selectedStore = {};
        });

route.js:

            .state('layout.orders', {
                url: '/orders',
                templateUrl: '/Content/js/apps/store/views/order.html',
                controller: 'orderController',
                controllerAs: 'orderVm',
                data: { pageTitle: 'Orders' }
            })

(將第一個選項留空是無濟於事的,但是首先要注意的是第一件事。)

我會使用ng-options,但坦率地說,它比這更晦澀。

https://jsbin.com/kanaco/edit?html,js,輸出

我為您編寫了示例代碼。 使用ng-options進行選擇。

編輯:

<select id="store" class="form-control input-inline input-medium" 
    ng-model="ctrl.selectedStores" 
    ng-options="item.MarketplaceName for item in ctrl.Stores"
    ng-init="ctrl.selectedStores=ctrl.Stores[0]">
</select>

您可以將ng-options用於重復選項,並將ng-init用於默認選擇。

切勿使用ng-repeat構建選擇選項。 而是使用ng-options ,它對此具有專用指令:

<select 
  id="store" 
  class="form-control input-inline input-medium"
  ng-model="orderVm.Stores.selectedStore"
  ng-options="store.ID as store.MarketplaceName for store in orderVm.Stores">
</select>

在您的控制器中,您需要為選擇模型分配一個默認值:

orderVm.Stores.selectedStore = 1;

這將導致在加載控制器時選擇Etsy選項。 請注意,這里的模型只是一個ID,您不需要使用對象。 您獲得空選項的原因是Angular無法將模型綁定到任何選項。

我遇到了一個您的問題非常相似的問題 ,並得到了一位善良的上師的幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM