angularjs中的日期以$ resource的形式发送.$ save()

Seb*_*ien 5 javascript angularjs

我有一个angularjs的问题.我创建了一个工厂事件,当我使用$ save方法时,d日期以UTC格式发送,而不是在浏览器时区中发送...

我创建了一个jsfiddle来说明它:

http://jsfiddle.net/Wr8mL/

(单击"保存"按钮并打开控制台以查看请求参数)

我的代码:

window.App = angular.module('App', ["ngResource"]);

App.factory('Event', ['$resource', '$http', function($resource, $http) {
  Event = $resource('/events/:id.json',
      { id:'@id' },
      { update: {method:'PUT' }, 'query': { method: 'GET', isArray: false }});
  return Event;
}])

App.controller("EventNewCtrl", ['$scope', "$http", "Event", function($scope, $http, Event) {

  $scope.resetEvent = function(){
    $scope.event = new Event({ date: new Date() })
  }

  $scope.save = function() {
      $scope.event.$save();
  }

  $scope.resetEvent()

}]);
Run Code Online (Sandbox Code Playgroud)

mic*_*ael 11

在提交数据之前,angular使用JSON.stringify函数转换对象.试试吧

console.log(JSON.stringify(new Date()));
Run Code Online (Sandbox Code Playgroud)

这与:

console.log(new Date().toISOString());
Run Code Online (Sandbox Code Playgroud)

(当然第一个将用引号括起来)

更改默认行为有很多可能性:

1)用你自己的实现替换toISOString函数:

  Date.prototype.toISOString = function(){
      return 'here goes my awesome formatting of Date Objects '+ this;
  }; 
Run Code Online (Sandbox Code Playgroud)

2)用你自己的替换角度的默认转换.您可以通过提供transformRequest函数(每个资源配置或整个应用程序$httpProvider.defaults.transformRequest)来实现此目的.有关更多信息,请参阅$ http服务.你的功能将如下所示:

transformRequest: function(data){
    return your string representation of the data
}
Run Code Online (Sandbox Code Playgroud)

如果你有兴趣为什么toISODate strip时区看一下ECMAScript Langauge规范:http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15