最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to use split in angularjs - Stack Overflow

programmeradmin1浏览0评论

im get date for ng-model like that

Thu May 21 2015 18:47:07 GMT+0700 (SE Asia Standard Time)

but it show me in console "TypeError: date.split is not a function" how to fix it?

   $scope.test = function(date) {
    console.log(date);
    $scope.d = (date.split(' ')[0]);
    $scope.m = (date.split(' ')[1]);
    $scope.y = (date.split(' ')[2]);
    $scope.dd = (date.split(' ')[3]);

}

im get date for ng-model like that

Thu May 21 2015 18:47:07 GMT+0700 (SE Asia Standard Time)

but it show me in console "TypeError: date.split is not a function" how to fix it?

   $scope.test = function(date) {
    console.log(date);
    $scope.d = (date.split(' ')[0]);
    $scope.m = (date.split(' ')[1]);
    $scope.y = (date.split(' ')[2]);
    $scope.dd = (date.split(' ')[3]);

}
Share Improve this question asked May 8, 2015 at 11:52 codeaddcodeadd 531 gold badge1 silver badge7 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

The problem is that date is not a String, it's a Date object instance. So you can't use split on it. In order to use it you might want to convert it to String first. For example like his:

$scope.test = function(date) {
    date = date.toString();
    $scope.d = (date.split(' ')[0]);
    $scope.m = (date.split(' ')[1]);
    $scope.y = (date.split(' ')[2]);
    $scope.dd = (date.split(' ')[3]);    
};

When you console log it console.log(date); it calls toString automatically that's why it looked like a string for you.

Another thing, you really should not use split to extract data. Use methods of the Date object, like getMonth, .getFullYear, etc.

Probably the date variable you get passed is not a string, but a Javascript Date object which has no split() method. You could go on and convert it to a string that you could split:

$scope.d = (date.toString().split(' ')[0]);

Which would work but not be very efficient, because the date would be posed to a string and then parsed again. Better would be using the properties of the date object itself:

$scope.d = date.getDate();
$scope.m = date.getMonth() + 1;
$scope.y = date.getFullYear();

and so on...

Find all the useable methods on the reference. Even better would be keeping the date itself as it is and just using the date properties where you need them in the view, for example:

<div class="myDate">Year: {{date.getFullYear()}}
发布评论

评论列表(0)

  1. 暂无评论