Search code examples
javascriptangularjsmomentjsangular-moment

Failed to instantiate module [module name] due to: Error: [$injector:modulerr]


I'm having an issue injecting moment.js into my module myApp. I have followed documentation from https://github.com/urish/angular-moment and https://www.npmjs.com/package/angular-momentjs but to no avail. Reading other similar questions and answers, it's likely it is down to an incorrect synatx but I can't see it. Any ideas?

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular-route.min.js"></script>
<script src="scripts/moment.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="scripts/angular-moment.js"></script>
<script src="scripts/app.js"></script>

<main ng-app="myApp" ng-controller="appCtrl">
    <div class="container">             
        <section class="ng-view">

        </section>
    </div>
</main>

var app = angular.module('myApp', ['ngRoute', 'angularMoment']);

app.controller('transCtrl', ['$scope', '$http', 'moment', function($scope, $http, moment){
    $http.get('../json/transactions.json')
    .then(function(response){
        $scope.transaction = response.data.transactions;
    }, function(errResponse){
        alert('error');   
    });

    $scope.sortType     = 'transId'; // set the default sort type
    $scope.sortReverse  = false;  // set the default sort order
    $scope.searchTrans   = '';     // set the default search/filter term

    $scope.date = new moment();

    console.log($scope.date)

}]);

Solution

  • since you are including moment.js and angular-moment from scripts folder, you should download those two files into scripts folder and make sure your server serve for scripts folder as static(this can be confirmed by checking network tag of your browser).

    the below example used online scripts and working fine.

    var app = angular.module('myApp', ['ngRoute', 'angularMoment']);
    
    app.controller('transCtrl', ['$scope', '$http', 'moment', function($scope, $http, moment) {
      $scope.date = new moment();
    
      console.log($scope.date)
    
    }]);
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular-route.min.js"></script>
    <!-- <script src="scripts/moment.js"></script> -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.0/moment.js"></script>
    <!-- <script src="scripts/angular-moment.js"></script> -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-moment/1.0.1/angular-moment.js"></script>
    
    <div ng-app="myApp" ng-controller="transCtrl">
      <div class="container">
    
      </div>
    </div>