Reputation: 13
I want to inject the momentJs library in my typescript code to do operations on a Date object. But I am not familiar with injecting typescript through angularJs, since it is little different from javascript.
angular.module("app")
.config(function ($mdDateLocaleProvider) {
$mdDateLocaleProvider.formatDate = function (date) {
return moment(date).format('YYYY-MM-DD');
};
});
In the above code, the moment
function is not recognized, even though I have included the CDN.
Upvotes: 1
Views: 2865
Reputation: 44
1 - Install moment with your package manager (NPM for example)
2 - Reference it in your entry point application file :
<script src="node_modules/moment/moment.js"></script>
3 - Create a constant referencing moment as it can be used as a service (don't forget to import it) :
import moment = require('moment');
angular.module("app").constant("moment", moment);
4 - You should be able now to configure moment in your angular run function like this :
angular.run(["moment", function(moment) { moment.locale("fr")}]);
AND using it in your controllers aswell still using dependency injection.
TIPS - Using typescript you should create your application using classes like this (even if Typescript is just a superset of Javascript) :
class MyController implements ng.IController {
static $inject: string[] : ["moment"];
constructor(
private moment) {}
$onInit = function () {
// do something with moment
let date = this.moment();
}
}
Let me know if it helps you out.
Upvotes: 1
Reputation: 110
You forgot to add moment in config callback. You have to add moment in config callback as you have added $mdDateLocaleProvider.
There is a more popular angular-moment. you can see the steps in documentation of angular-moment. https://github.com/urish/angular-moment
let me know if any thing else is required
Upvotes: 0
Reputation: 1276
After you add all necessary scripts of moment.js in your page.
Use it like this and try
angular.module("app")
.config(function ($mdDateLocaleProvider, moment) {
$mdDateLocaleProvider.formatDate = function (date) {
return moment(date).format('YYYY-MM-DD');
};
});
Upvotes: 0