如何从json AngularJS日期

Fla*_*ira 7 formatting date angularjs

我是angularjs的新手我试图将日期属性绑定到输入(文本)但我不知道如何格式化日期.

我的json对象控制器:

$scope.datasource = {"prop1":"string data", "myDateProp":"\/Date(1325376000000)\/"}
Run Code Online (Sandbox Code Playgroud)

我的看法:

<input type="text" ng-model="datasource.myDateProp" />
Run Code Online (Sandbox Code Playgroud)

结果,我在我的文本框中得到字符串"/ Date(1325376000000)/".

我该如何格式化这个日期?

gan*_*raj 3

您需要做的是查看http://docs.angularjs.org/api/ng.filter:date这是一个默认情况下在 Angular 中可用的过滤器。

您似乎正在通过日期传递额外的内容。请参阅此处的场景。( /日期(*)/ ) 。除了 * 中的内容之外,其他所有内容都不需要解析日期,并且默认的角度过滤器将无法解析它。要么从模型中删除这些额外的内容,要么您可以编写自己的过滤器以在输入时删除它们。

编辑 :

看看http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController(以及那里定义的示例!)。如果您打算在多个地方重用它,我建议您在 ngModelController 描述的方法中执行此操作。创建一个新指令并在 ngModel 上实现 $render 和 $setViewValue。

如果您只想在一个地方执行此操作,那么另一种方法是为输入定义一个新模型。就像是

$scope.dateModel = "";
Run Code Online (Sandbox Code Playgroud)

并使用它

<input type="text" ng-model="dateModel" ng-change="onDateChange()"/>
Run Code Online (Sandbox Code Playgroud)

在您的控制器中,您必须执行以下操作:

$scope.$watch("datasource.myDateProp",function(newValue){

    if(newValue){
        convert(newValue);
    }
});

function convert(val){
    //convert the value and assign it to $scope.dateModel;
}


$scope.onDateChange = function(){
// convert dateModel back to the original format and store in datasource.myDateProp.
}
Run Code Online (Sandbox Code Playgroud)