angular ng-model 中接收后台的时间戳格式化

来源:互联网 发布:手机自动作曲软件 编辑:程序博客网 时间:2024/06/06 01:49

1,将input 上的后天传回的时间戳格式化年月日,首先在网上百度各种,有的说不用ng-model ,直接用value,在valeu中将入过滤器,应为ng-model是不能直接加过滤器的展示代码如下:

<input type="text" class="form-control accepTime" id="accepTime{{$index}}" placeholder="" value="{{g.accepTime |date:'yyyy-MM-dd'}} "style="cursor: pointer;">

时间是格式化了,但是不能双向绑定了,向后台传入时间,故此方法不能达到我想要的目的.

2.自定义指令,代码如下:

<input type="text" class="form-control accepTime " id="accepTime{{$index}}" ng-model="g.accepTime"date-format  style="cursor: pointer;">

 var financeSupportApp = angular.module("financeSupportApp",[])

.directive('dateFormat', ['$filter',function($filter) {  
         var dateFilter = $filter('date');
         return {  
        restrict: 'AEC',
        require: 'ngModel',  
        link: function(scope, elm, attrs, ctrl) {  
 
            function formatter(value) {  
                return dateFilter(value, 'yyyy-MM-dd'); //format  
            }  
 
            function parser() {  
                return ctrl.$modelValue;  
            }  
 
            ctrl.$formatters.push(formatter);  
            ctrl.$parsers.unshift(parser);  
 
        }  
    };  
        
       }])

此方法也可以实现格式化时间,此时ng-model的双向绑定被破坏

3.然后自己思索另一种方法,直接在js中对查出的时间循环,将每一个时间加时间过滤器,解决了时间前台显示是格式化的时间,也没有破坏双向绑定,代码如下:

前台代码如下:

刚接触angular,不大熟悉,可能表达的不是很全面,只是想记录下自己遇到的问题,和解决思路,同时也希望对遇到同样问题的朋友有点帮助.