Reputation: 117
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
Upvotes: 0
Views: 894
Reputation: 124
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).
Upvotes: 0
Reputation: 4191
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>
Upvotes: 1