Search code examples
javascriptangularjsnode.jsmomentjsangular-moment

How to run this moment.js code from node.js to angular.js controller?


I have this node.js code below;

var moment = require('moment')
var myDate = new Date("2008-01-01");
myDate.setMonth(myDate.getMonth() + 13);
var answer = moment(myDate).format('YYYY-MM-DD');

I would like to run it in angularjs. I followed the instructions in https://github.com/urish/angular-moment and have added the necessary links and modules.

I would like to run the code in my angularjs controller.

angular.module('myApp.controllers', [])
    .controller('OwnCtrl', ['$scope', '$http', '$timeout', '$window', 'configuration', 
                            function($scope, $http, $timeout, $window, $configuration) 
{
}

Problem is I cannot call var moment = require('moment') in angularjs, unlike in node.js. How can this be done inside an angularjs controller?


Solution

  • You can't use Node.js module on Angular code, but you can install angular-moment, inject files and dependencies as stated in the README and the use it like this:

    angular.module('myApp.controllers', []).controller('OwnCtrl', ['$scope', '$http', '$timeout', '$window', 'configuration', 'moment',
    function ($scope, $http, $timeout, $window, $configuration, moment) {
        var myDate = new Date("2008-01-01");
        myDate.setMonth(myDate.getMonth() + 13);
        var answer = moment(myDate).format('YYYY-MM-DD');
    }]);