0

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.

2
  • Ad "Working Example": The date filter converts a date to a string, not the other way around. As for your question, we don't know what the "dateFromNow" filter does and what input it expects. Commented Jun 3, 2016 at 10:30
  • @zeroflagL - Thanks for letting me know. I have made an edit to my question to add the filter. It's very basic, just uses MomentJS. Commented Jun 3, 2016 at 10:33

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Your working example uses the date filter, not the filter from the question.
Right! I just forked the example from a link "Working Example" provided in the question.
Perfect, thanks Lukasz. Will have to keep that in mind.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.