Hiero
Hiero

Reputation: 2205

AngularJS data model architecture

I have the following thing on my Angular app:

$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));
};

And on the HTML part:

<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>

When press the Clone button I'm pushing a new element to form.input array and add a new input to the DOM.

I want to $http.post all the values for the inputs.

I know to push something I need to use

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

But I dont know how to make an object from all the .item inputs.

Can someone explain me how or suggest a better solution?

Upvotes: 0

Views: 247

Answers (1)

michelem
michelem

Reputation: 14590

If you use a ng-model for your inputs and set it to an object you can then inject that object to the post, here is a really basic example:

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
    };

}]);

Upvotes: 1

Related Questions