AngularJS之ng-options的best practise

廢話很少說,直接上代碼。javascript

function MySelectCtrl($scope)
{
  $scope.Model = [
    {
      id: 10002,
      MainCategory: '男',
      ProductName: '水洗T恤',
      ProductColor: '黑'
    },
    {
      id: 10004,
      MainCategory: '女',
      ProductName: 'V領短袖',
      ProductColor: '紅'
    },
    {
      id: 10006,
      MainCategory: '男',
      ProductName: '圓領長袖',
      ProductColor: '白'
    }];
  
  $scope.selected = 10002;
}

  

<select ng-model="selected" ng-options="m.id as (m.ProductColor + ' - ' + m.ProductName) for m in Model">
  <option value="">-- 選擇一個試試 --</option>
</select>
  • 建議不要直接傳resource給api,儘可能是字符串或整型(好比綁定的是ng-model="selected")
  • 不要管angular生成出來的<option>...</option>中的value是啥,想傳什麼值給後端就在ng-options=""中的第一個參數寫,如本例是m.id
  • ngOptions 自動選中是根據reference來的,因此ng-model中綁定的值應當是與options數組同源以下:
$scope.getBeacon = function (id) {
  return Beacon.get({id: id}).$promise;
};

$scope.getVendors = function () {
  return Vendor.query({}).$promise;
};

$q.all([$scope.getVendors(), $scope.getBeacon($scope.beacon.id)])
  .then(function (promises) {
    $scope.vendors = promises[0];
    $scope.beacon = promises[1];
    $scope.beacon.vendor = $scope.vendors[_.findIndex($scope.vendors, $scope.beacon.vendor)];
});


// HTML
<div class="form-group">
  <label for="vendor">廠家</label>
  <select class="form-control" id="vendor" ng-model="beacon.vendor" ng-options="vendor as vendor.name for vendor in vendors">
<option value="" ng-if="!beacon.vendor">-- 請選擇廠家 --</option>
</select>
</div>

 

寫下這些但願再不要再被angular的默認選中和傳值問題干擾了!html

相關文章
相關標籤/搜索