【问题标题】:AngularJS data model architectureAngularJS 数据模型架构
【发布时间】:2015-08-25 16:25:12
【问题描述】:

我的 Angular 应用程序中有以下内容:

$scope.things = [{
   title: 'Simple',
   type: 1,
   form: {
         input: [1, 2, 3],                        
         clone: true
      }
}];

$scope.clone = function(item) {
   item.form.input.push(Math.floor(Math.random() * 999));
};

在 HTML 部分:

<div ng-repeat="item in things" class="item">
   <h2>{{item.title}}</h2>
   <div ng-repeat="input in item.form.input">
       <input type="text" />
   </div>
   <button ng-click="cloneInput(item)">Clone</button>
</div>

当按下 Clone 按钮时,我将一个新元素推送到 form.input 数组并向 DOM 添加一个新输入。

我想 $http.post 输入的所有值。

我知道推送我需要使用的东西

$http.post('/path/to/my/api', {my object}).callback()

但我不知道如何从所有 .item 输入中创建一个对象。

谁能解释我如何或提出更好的解决方案?

【问题讨论】:

  • 这真的取决于你的后端如何接受数据。在前端,你有数组,然后你可以随意格式化它。

标签: javascript json angularjs datamodel


【解决方案1】:

如果您使用ng-model 作为输入并将其设置为一个对象,您就可以将该对象注入到帖子中,这是一个非常基本的示例:

JSFiddle

HTML:

<div ng-app="myApp" ng-controller="dummy">
    <div ng-repeat="input in items">
        <input type="text" name="{{input.name}}" ng-model="data[input.name]" />
    </div>
    <button ng-click="submit()">Submit</button>
    <p ng-show="displayIt">{{data}}</p>
</div>

JS:

angular.module('myApp', [])
    .controller('dummy', ['$scope', function ($scope) {
    $scope.items = [{
        name: 'test'
    }, {
        name: 'test2'
    }];

    $scope.data = {};
    $scope.displayIt = false;
    $scope.submit = function () {
        // This is only to check it
        $scope.displayIt = true;
        // Do your post here
    };

}]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-21
    • 1970-01-01
    • 1970-01-01
    • 2019-12-30
    • 1970-01-01
    • 1970-01-01
    • 2010-09-22
    • 1970-01-01
    相关资源
    最近更新 更多