Fizzix Fizzix - 6 months ago 375
AngularJS Question

Angular parse error - Token is an unexpected token

I have created a basic

directive
that updates the time within a div:

myApp.directive('updateTime', function($timeout, $filter) {
return function(scope, element, attrs) {
var timeoutId;

function updateTime() {
element.text($filter('dateFromNow')(attrs.updateTime));$()
}

scope.$watch(attrs.updateTime, function(value) {
updateTime();
});

function updateLater() {
timeoutId = $timeout(function() {
updateTime();
updateLater();
}, 5000);
}

element.bind('$destroy', function() {
$timeout.cancel(timeoutId);
});

updateLater();
}
});


My model contains a date object, like so
2016-06-03T09:14:57.948Z
, yet Angular seems to be complaining about it being in that format. It is how my database (MongoDB) delivers the date.

Error: $parse:syntax
Syntax Error
Syntax Error: Token 'T09' is an unexpected token at column 11 of the expression [2016-06-03T09:14:57.948Z] starting at [T09:14:57.948Z].


How can I get around this error?

WORKING EXAMPLE

EDIT:

This is my
dateFromNow
filter. It simply just converts a date object (or date string) to a
time ago
string (such as "2 minutes ago") with MomentJS:

myApp.filter('dateFromNow', function () {
return function (date, onlyFromNow) {
return moment(date).fromNow();
}
});


In my console, I can see that the error occurs within my
scope.$watch(....
within my directive.

Answer

The error gets thrown from scope.$watch because you are passing the actual value (2016-06-03T09:14:57.948Z) while it needs to know a name (or path) of the variable.

You can fix it with a few modifications.

Use your directive like below:

<div update-time="myTime">

Get the attribute value in updateTime() by parsing it:

 $parse(attrs.updateTime)(scope)

This requires the $parse service to be injected to your directive:

.directive('updateTime', function($timeout, $filter, $parse) {
    // ...
})

Here is a working example: http://codepen.io/LukaszWiktor/pen/BzNLOM