在对象内插入格式化日期

时间:2017-08-11 17:01:44

标签: javascript angularjs

我正在为初学者学习AngularJS,我想插入Date()函数,格式为' MMM d,y'在object.date属性中?

<script>
var app = angular.module('myApp', []);
app.controller('datCtrl', function($scope) {
  $scope.Info = {
    author: "",
    rating: 5,
    comment: ""
  };
  $scope.x = Date();
  $scope.today = $filter('date')($scope.x)]; $scope.Info.date = $scope.today;
});
</script>

1 个答案:

答案 0 :(得分:0)

你有一个错字,但这里是你如何处理Angularjs中的日期。我注意到有人提到了moment.js这是一个可靠的库,但可能比你需要的多一点。确保将$filter注入控制器。

试试这个:

<script>
var app = angular.module('myApp', []);
app.controller('datCtrl', function($scope, $filter) {
  $scope.Info = {
    author: "",
    rating: 5,
    comment: ""
  };

  $scope.today = $filter('date')(new Date(), 'MMM d, y'); 
  $scope.Info.date = $scope.today;
});
</script>

这是一个代码较少的超简化版本。

<script>
var app = angular.module('myApp', []);
app.controller('datCtrl', function($scope, $filter) {
  $scope.Info = {
    author: "",
    rating: 5,
    comment: "",
    date: $filter('date')(new Date(), 'MMM d, y')
  };
});
</script>