1

I have an array in my controller containing date-objects called $scope.events. I would like to iterate these events and and print them out in a certain format, which I use momentjs for.

Now the thing is, I cannot get it to actually use momentjs.

I have tried the following:

<table>
   <tr ng-repeat="ev in events">
    <td>{{ moment(ev).format("HH") }}</td>
   </tr>
</table>

but this just prints an empty cell.

So my question is, how do I use javascript, momentjs, inline in my angular-binding ?

thanks

Thomas

3
  • Will work only if moment is declared as a member of $scope: $scope.moment = moment;. Commented Feb 21, 2014 at 23:37
  • Also, just as a note on good AngularJS practice, it might be worth wrapping momentjs in an Angular service and using that. Commented Feb 21, 2014 at 23:37
  • try as well: <td>{{ moment(ev) | date 'HH' }}</td> where moment under $scope Commented Feb 21, 2014 at 23:38

2 Answers 2

2

Assuming moment is a property of window, you'll need to create a reference in this object's $scope that references moment.

Very simply:

$scope.moment = window.moment;

Here's a plunkr showing internal $scope methods vs. a $scope property referencing a method on window:

http://embed.plnkr.co/PWFK80/preview

That's the simple answer, but you'd likely want to wrap this library into its own directive or service, so that you could use it without coupling higher-level objects to the window object unnecessarily.

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

Comments

1

Wrap the code in a function in your controller for a quick answer.

controller('Ctrl', function($scope) {
  $scope.moment = moment;
});

I edited this to match a comment by @Stewie because it looks better

and in your html:

<td>{{moment(ev, 'HH'}}</td>

Or make a service/directive for moment for something better.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.