Angular JS Date过滤器无法正常工作

dev*_*evo 23 angularjs angularjs-ng-repeat angularjs-filter

我有一个ng-repeat循环$http.get()结果的元素.

<tr ng-repeat="blog in posts">
     <td style="text-align:center">{{ $index+1 }}</td>
     <td>{{ blog.title }}</td>
     <td>
         {{ blog.author.name }}
     </td>
     <td>
         {{ blog.created_at | date:'MMM-dd-yyyy' }}
     </td>
</tr>
Run Code Online (Sandbox Code Playgroud)

created_at作为timestamp在MySQL数据库中的表.而我正在使用angular.js v1.0.7.

我从db表获取相同的输出并且日期过滤器不起作用.我怎么解决这个问题?

我的ajax电话,

$http({method: 'GET', url: 'http://localhost/app/blogs'}).
success(function(data, status, headers, config) {
    $scope.posts = data.posts;
}).
error(function(data, status, headers, config) {
    $scope.posts = [];
});
Run Code Online (Sandbox Code Playgroud)

Ano*_*yes 41

传递给过滤器的日期必须是javascript Date类型.

blog.created_at没有过滤器检查过显示的值是什么?

您说您的支持服务返回一个表示日期的字符串.您可以通过两种方式解决此问题:

  1. 使服务器端代码返回json日期对象
    • 检查服务器端代码如何序列化它返回的json
  2. 编写自己的过滤器,接受字符串日期并以所需格式返回日期
    • 注意:您可以在自己的过滤器中调用角度过滤器

您可以按如下方式编写自己的过滤器:

app.filter('myDateFormat', function myDateFormat($filter){
  return function(text){
    var  tempdate= new Date(text.replace(/-/g,"/"));
    return $filter('date')(tempdate, "MMM-dd-yyyy");
  }
});
Run Code Online (Sandbox Code Playgroud)

并在模板中使用它:

<td>
  {{ blog.created_at | myDateFormat }}
</td>
Run Code Online (Sandbox Code Playgroud)

而不是循环返回返回的数组,然后应用过滤器


dev*_*evo 15

从服务器端,它created_at从laravel eloquent 返回as字符串.

这可以使用这个javascript来解决,

new Date("date string here".replace(/-/g,"/"));
Run Code Online (Sandbox Code Playgroud)

所以代码,

$http({method: 'GET', url: 'http://localhost/app/blogs'}).
success(function(data, status, headers, config) {
   angular.forEach(data.posts, function(value, key){
     data.posts[key].created_at = new Date(data.posts[key].created_at.replace(/-/g,"/"));
   }
   $scope.posts = data.posts;
}).
error(function(data, status, headers, config) {
    $scope.posts = [];
});
Run Code Online (Sandbox Code Playgroud)


小智 8

您可以添加将字符串转换为日期的自定义过滤器,如下面的代码:

app.filter('stringToDate',function ($filter){
    return function (ele,dateFormat){
        return $filter('date')(new Date(ele),dateFormat);
    }
})
Run Code Online (Sandbox Code Playgroud)

然后在任何模板中使用此过滤器,如下代码:

<div ng-repeat = "a in data">{{a.created_at |stringToDate:"medium"}}</div>
Run Code Online (Sandbox Code Playgroud)


Max*_*tin 6

您可以new Date(/*...*/)根据从中获取的数据进行创建$http.get,例如:

$scope.date = new Date('2013', '10', '28'); // for example
Run Code Online (Sandbox Code Playgroud)

无论如何你可以看到这个演示Plunker.

希望它会对你有所帮助