date - 如何从json中获取AngularJS日期

标签 date formatting angularjs

我是 angularjs 的新手,我正在尝试将日期属性绑定(bind)到输入(文本),但我不知道如何格式化日期。

我的 json 对象 Controller :

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

我的看法:

<input type="text" ng-model="datasource.myDateProp" />

结果,我在我的文本框中得到了字符串“/Date(1325376000000)/”。

如何格式化这个日期?

最佳答案

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

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

编辑:

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

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

$scope.dateModel = "";

并使用它

<input type="text" ng-model="dateModel" ng-change="onDateChange()"/>

在您的 Controller 中,您必须执行以下操作:

$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.
}

关于date - 如何从json中获取AngularJS日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12837783/

相关文章:

java - 及时跟踪虚构日期的最佳类(class)? ( java )

java - 使用 Eclipse Code Formatter for Java 在 if() 中的条件缩进

java - 当负数包含括号时,如何使字符串值总和为 Big.Decimal?

java - 打开文件时如何在 emacs 中自动缩进?

java - 使用日历当前日期设置对象

php - Javascript 时间转换为 PHP 时间

javascript - 夏令时 JavaScript 格式化日期

angularjs - ui-router 嵌套 View 访问多个 Controller

javascript - ionic 单选按钮 - Controller 范围无法识别更改

javascript - Angular 函数不更新数据库