AngularJS - 使用Select元素从另一个对象获取Id的表单

时间:2015-07-05 14:12:19

标签: javascript angularjs

我有两张桌子"类别"和"出版物"与一对多的关系。

类别: ID,名称,说明

发布: id,title,content,category_id

我需要通过select元素获取类别ID并将其放在category_id字段中。

出版形式:

<form>
  <input type="text" ng-model="publication.title" placeholder="Title" />
  <input type="text" ng-model="publication.content" placeholder="Content" />
  <!-- Here is my problem because I can list all categories but I can't get the category id and put it in the category_id field -->
  <div ng-init="categories()">
    <select class="form-control" ng-model="category" ng-options="category.name for category in categories">
        <option value="">-- Select category --</option>
    </select>
   </div>
</form>

这是我的控制器以获取所有类别:

$scope.categories = function() {
    $http(
            {
                method : 'GET',
                url : '/prodemo/category'
            }).success(
                    function(data, status, headers, config) {
                        $scope.categories = data;
            }).error(
                    function(data, status, headers, config) {
            });
};

我该怎么做?

2 个答案:

答案 0 :(得分:2)

如下所示,隐藏字段可以轻松实现

    <form>
      <input type="text" ng-model="publication.title" placeholder="Title" />
      <input type="text" ng-model="publication.content" placeholder="Content" />
      <input type="hidden" ng-model="publication.category_id = category.id" />

      <div ng-init="categories()">
        <select class="form-control" ng-model="category" ng-options="category.name for category in categories">
            <option value="">-- Select category --</option>
        </select>
       </div>
    </form>

答案 1 :(得分:1)

var id = Guid.NewGuid(); 

在控制器中:

<select class="form-control" ng-change="getPubs()" ng-model="category" ng-options="category.name for category in categories">
    <option value="">-- Select category --</option>
</select>
<select class="form-control" ng-model="selected_pub" ng-options="pub.name for pub in publications">
    <option value="">-- Select Pub --</option>
</select>