【问题标题】:How to run this moment.js code from node.js to angular.js controller?如何将这个 moment.js 代码从 node.js 运行到 angular.js 控制器?
【发布时间】:2015-10-31 07:17:58
【问题描述】:

我在下面有这个 node.js 代码;

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

我想在 angularjs 中运行它。我按照https://github.com/urish/angular-moment 中的说明添加了必要的链接和模块。

我想在我的 angularjs 控制器中运行代码。

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

问题是我不能在 angularjs 中调用 var moment = require('moment'),这与 node.js 不同。这如何在 angularjs 控制器中完成?

【问题讨论】:

    标签: javascript angularjs node.js momentjs angular-moment


    【解决方案1】:

    您不能在 Angular 代码上使用 Node.js 模块,但您可以安装 angular-moment、注入文件和依赖项,如 README 中所述并像这样使用它:

    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');
    }]);
    

    【讨论】:

    • 定义模块时还需要注册对angularMoment的依赖
    【解决方案2】:

    您需要按如下方式更改您的代码:

    angular.module('myApp.controllers', ['angularMoment'])
        .controller('OwnCtrl', ['$scope', '$http', '$timeout', '$window', 'configuration', 'moment', 
                                function($scope, $http, $timeout, $window, $configuration, moment) 
    {
        //use as in node
        var newDate = moment();
    }
    

    在这种情况下,您使用普通的 angular-js 依赖注入

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-22
      • 2017-04-25
      • 1970-01-01
      相关资源
      最近更新 更多