Search code examples
javascriptangularjsmomentjsangular-moment

angular-moment not working via dom injection


I have a page with angular-moment on it. Upon page rendering angular-moment is working. Using

<span am-time-ago="message.time"></span>

But when I append new html.. it's not working

   var date = '<span am-time-ago=\"message.time\"></span>';
   angular.element('#here').append(date);

Did I missed something? Please help...

Thanks, Kurai


Solution

  • HTML that is appended manually must be bound to a $scope.

    To do this you inject and use the $compile service.

    // Pass element or HTML string to `$compile` to get a link function
    var linkFn = $compile('<span am-time-ago="message.time"></span>');
    
    // Pass `$scope` to the link function to get an element bound with it
    var element = linkFn($scope);
    
    // Append the element
    angular.element('#here').append(element);
    

    It's often written like this:

    var element = $compile('<span am-time-ago="message.time"></span>')($scope);
    angular.element('#here').append(element);
    

    Note that if you must add HTML manually like this and want to follow the best practices of Angular, it should be done from a directive.