0

我有日期时间字段和状态(开/关)字段的表单,我将它们组合在一个 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"}]

在每个按钮单击时将对象添加到数组

4

2 回答 2

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>

于 2018-09-05T15:14:45.303 回答
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'也应该工作)。

于 2018-09-05T15:31:41.090 回答