我有一个带有datetime字段和status(on / off)字段的表单,我将它们组合在一个json对象{"time":"2002-03-01T03:01:00.000Z","status":"off"}
中
onclick添加按钮,我需要将此对象添加到json数组
结果应该是这样的:
[{"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"}]
在每个按钮单击中将对象添加到数组中
答案 0 :(得分:1)
您对它的外观不太清楚,但是您只需要在控制器中的某个位置插入array.push(object)
,就可以通过ng-click
在某个按钮上调用它。
这是一个演示:
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>
答案 1 :(得分:0)
您可以这样做
<input type="text" ng-model="$scope.jsonStyleObject">
<button ng-model="$scope.jsonStyleObject"ng-click="addItemFunction($scope.jsonStyleObject)">Add to array of
objects</button>
在视图中使用ng-click
可以在控制器中调用一个函数(我的首选方法是使用“ vm。”,但也可以使用“ $ scope”)。