使用ng-submit和ng-model与嵌套的javascript对象

时间:2014-02-02 23:40:05

标签: javascript angularjs directive

LIVE CODE JSBIN

我有一个表单和一组名为Templates.row的数据。我想使用表单将用户输入的数据推送到Templates.row而不是内部对象Templates.row.touts

所以有两个问题: 我可以使用我的addTout()函数将表单提交到templates.row {}:

.controller("templatesCtrl", function ($scope, Templates) {

    $scope.template = Templates;

    $scope.addTout = function() {
      $scope.template.row[$scope.ap.id] = $scope.ap;
      delete($scope.ap);
    };
});

但是我想在templates.row.touts中创建:

angApp.factory("Templates", function () {
    var Templates = {};
    Templates.row = {
        touts : [
            {
                'slug' : 'slug1',
                'classes' : ['col-12', 'col-md-3', 'col-lg-3' ],
                'staticImg' : 'images/guy-1.3.jpg',
                'caption' : 'LIGHTWEIGHT STYLE',
                'subCaption' : 'Shop Nike Tech Pack'
            },
            {
                'slug' : 'slug2',
                'classes' : ['col-12', 'col-md-9n', 'col-lg-9n' ],
                'staticImg' : 'images/shoe-sing.jpeg',
                'caption' : 'THE NIKE KNOWS COLLECTION. AVAILABLE NOW.',
                'subCaption' : 'Kicks of the Week: Explore the complete Nike Knows Collection'
            }
        ]
  };
    return Templates;
});

正如你所看到的那样,它被设置在touts之外(并且未定义,我不知道为什么/这意味着什么) wrong place 不幸的是,当我将addTout()函数更改为:

    $scope.addTout = function() {
      $scope.template.row.touts[$scope.ap.id] = $scope.ap;
      delete($scope.ap);
    };

它不起作用。那么如何更改我的addTout()以推送并在touts数组中创建一组新数据。

下一个问题是密钥:classes有一个数组。我如何在表单中支持这个数组,以便正确存储。

<form ng-submit="addTout()" ng-model="ap" >
      <h4 >Add Tout</h4>
      <div class="form-group">
        <label>slug:</label><br>
        <input class="form-control" type="text" ng-model="ap.slug" placeholder="eg. PDX">
      </div>

       <div class="form-group ">
         <label >classes:</label><br>
        <input class="form-control" type="text" ng-model="ap.classes" placeholder="e.g. col-12">
          <input class="form-control" type="text" ng-model="ap.classes" placeholder="e.g. col-md-12">
          <input class="form-control" type="text" ng-model="ap.classes" placeholder="e.g. col-lg-12">
      </div>

      <div class="form-group">
        <label>image:</label><br>
        <input class="form-control" type="text" ng-model="ap.image" placeholder="eg. Portland Intl. Airport">
      </div>

      <div class="form-group">
        <label>caption</label><br>
        <input  class="form-control"type="text" ng-model="ap.caption" placeholder="eg. Portland">
      </div>

      <div class="form-group">
        <label>Sub Caption</label><br>
        <input  class="form-control"type="text" ng-model="ap.subcaption" placeholder="eg. Portland">
      </div>

  <input class="btn btn-primary" type="submit">
    </form>

1 个答案:

答案 0 :(得分:1)

由于标题是一个数组,您应该使用以下命令分配新条目:

$scope.template.row.touts.push($scope.ap);

这会将其正确地添加为新的tout。您收到未定义密钥的原因是$scope.ap.id似乎没有被分配到任何地方,我可以看到。