angularjs获取ng-options obj id而不是value

时间:2017-02-18 05:07:56

标签: javascript angularjs

      <select ng-model="ad.Categorie"
              ng-options="obj.id as obj.name for obj in categories"
              ng-change="getSubcategories()"
              class="form-control"
              ng-required="true"
              name="categorie">
        <option value="">--  --</option>
      </select>

当我提交获取ng-options数组索引而不是ad.Categorie值时,我用隐藏输入解决了

<input type="hidden" name="categorie" value="@{{ad.Categorie}}" />

但任何想法似乎都是错误的解决方案?

var categories = [{"id":1,"name":"cat1"},{"id":2,"name":"cat2"}];

从数据库中读取。我希望类别ID为fk

    public function store(Request $request)
{
    $ad = new Ad;
    $ad->categorie_id= $request->categorie;
    $ad->subcategorie_id= $request->subcategorie;
    $ad->type_id= $request->type;
    $ad->location_id= $request->location;
    $ad->title= $request->title;
    $ad->description= $request->description;
    $ad->price= $request->price;
    $ad->phone= $request->phone;
    $ad->code= $request->code;
    //$ad->img = $request->file('img');
    //$files = $request->file('img');
    $ad->save();
    return redirect('/');
}

这个数组是$ request-&gt;类别,这就是为什么我得到索引?

1 个答案:

答案 0 :(得分:0)

您的代码已经正确id,我假设您想要获取对象或索引。这段代码用于获取索引,id和对象:

   <select ng-model="ad.Categorie" 
    ng-options="obj.name for obj in categories" 
    ng-change="getSubcategories()" 
    class="form-control" 
    ng-required="true" 
    name="categorie">
   </select>

在您的控制器中:

function myCtrl($scope) {
  $scope.categories = [{
    "id": 11,
    "name": "name1"
  }, {
    "id": 22,
    "name": "name2"
  }];
  $scope.ad = {}
  $scope.getSubcategories = function() {
    console.log("selected object= ", $scope.ad.Categorie);
    console.log("selected index= ", $scope.categories.indexOf($scope.ad.Categorie));
    console.log("selected id= ",$scope.ad.Categorie.id);
  }
}

以下是工作示例: https://jsfiddle.net/U3pVM/30048/