0

我在我的項目中使用ui bootstrap datepicker,當我從數據庫中獲取的數據在此日期值Thu Aug 11 2016 00:00:00 GMT+0530 (India Standard Time)的類型是string當我使用UI引導日期選擇不採取JS日期()對象的字符串

new Date('Thu Aug 11 2016 00:00:00 GMT+0530 (India Standard Time)');

然後它工作正常,我不想在controller使用new Date();轉換它,我實際上想要使用directivefilter來實現此轉換我怎麼能實現這一目標?我的日期選擇器領域是:

<input type="text" class="form-control custom-form-control" uib-datepicker-popup="{{format}}" ng-model="moduleName.main.expiryDate" is-open="expiryDateCal.opened" datepicker-options="expiryDateOptions" name="expiryDate" ng-required="true" close-text="Close"/> 
+1

你可以寫一個'filter'並將其追加到'NG-model'這將返回日期對象只需添加'新的日期(「星期四2016年8月11日00:00: 00 GMT + 0530(印度標準時間)');'在你的過濾器 –

+0

我喜歡這個想法,我同意你的意見,但是我不知道如何在'ng-model'中追加'filter'這是我唯一的問題。 –

+0

使用指令而不是過濾器添加了答案,因爲您正在使用datepicker,它需要ng-model與where指令一起玩,讓您獲得更多優勢 –

回答

2

使用過濾器是不是在與ng-model。所以的情況下是一個好主意,而不是我創建了字符串轉換日期Date對象一個指令。

運行代碼示例以檢查工作。希望這有助於您,只需根據需要使用ng-model將date屬性添加到HTML標記。

var app = angular.module('app',[]); 
 
app.controller('Ctrl',function($scope,$filter){ 
 
    
 
    $scope.date="Thu Aug 11 2016 00:00:00 GMT+0530 (India Standard Time)"; 
 
    
 
    }); 
 

 
app.directive('date', function(dateFilter) { 
 
    return { 
 
    require: 'ngModel', 
 
    
 
    link: function(scope, element, attrs, ngModelController) { 
 
     ngModelController.$parsers.push(function(data) { 
 
     //convert data from view format to model format 
 
     return new Date(data); //converted 
 
     }); 
 

 
     ngModelController.$formatters.push(function(data) { 
 
     //convert data from model format to view format 
 
     return new Date(data); //converted 
 
     }); 
 
    } 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="app" class="widget-content" ng-controller="Ctrl"> 
 

 
    <input type="text" ng-model="date" date/> 
 
    </div>

相關問題