0

I have form with datetime field and status(on/off) field, I have combined them in one json object {"time":"2002-03-01T03:01:00.000Z","status":"off"} onclick add button I need to add this opject to json array the result should be like this:

[{"time":"2002-03-01T03:01:00.000Z","status":"off"},
{"time":"2002-03-01T03:01:00.000Z","status":"on"},
{"time":"2002-03-01T03:01:00.000Z","status":"off"},
{"time":"2002-03-01T03:01:00.000Z","status":"on"}]

adding object to array in each button click

1
  • what have you tried so far Commented Sep 5, 2018 at 15:03

2 Answers 2

1

You are not very clear about what you want it to look like, but you just need array.push(object) somewhere in your controller, which can be called from ng-click on some button.

Here is a demo:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.array = [{
      "time": "2002-03-01T03:01:00.000Z",
      "status": "off"
    },
    {
      "time": "2002-03-01T03:01:00.000Z",
      "status": "on"
    },
    {
      "time": "2002-03-01T03:01:00.000Z",
      "status": "off"
    },
    {
      "time": "2002-03-01T03:01:00.000Z",
      "status": "on"
    }
  ];

  $scope.add = function(object) {
    $scope.array.push(object);
    $scope.st = null; // reset
  }
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
  <div ng-app="myApp" ng-controller="myCtrl">

    Time: <input ng-model="tm" type="datetime-local" /><br>
    Status: <select ng-model="st" ng-options="x for x in ['on','off']"></select><br>
    <button ng-click="add({'time':tm,'status':st || 'off'})">Add</button>
    
    <hr>
    <div ng-repeat="obj in array">
      Time: {{obj.time | date}}, status: {{obj.status}}
    </div>
    <hr>
    <pre>{{array | json}}</pre>

  </div>
</body>

</html>

Sign up to request clarification or add additional context in comments.

Comments

0

You could do something like this

<input type="text" ng-model="$scope.jsonStyleObject"> 

<button ng-model="$scope.jsonStyleObject"ng-click="addItemFunction($scope.jsonStyleObject)">Add to array of 
objects</button>

using ng-click in the view you can call a function in your controller(my preferred method is using 'vm.', however '$scope' should work too).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.