Angularjs:未捕获的ReferenceError $ rootScope未定义

时间:2016-10-10 05:24:28

标签: javascript jquery angularjs ngroute angularjs-rootscope

我正在尝试运行并收到此消息:

  

未捕获的ReferenceError:$ rootScope未在app.js第12行定义

这是我的js / app.js

angular.module('addEvent', ['ngRoute'])
    .config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
        $routeProvider.when('/add-event', {
                templateUrl: 'views/add-event.html',
                controller: 'formCtrl',
                controllerAs: 'eventCtl'
            })
            .otherwise({
                redirectTo: '/'
            });
        $locationProvider.html5Mode(true);
    }])
    .run(['$rootScope', function() {
        $rootScope.event = [];
    }]);

这是js / controller.js

  angular.module('addEvent')
      .controller('formCtrl', ['eventFactory', function(eventFactory) {
          //$scope.event=[];
          this.event = eventFactory.getAllEvents();
          this.submitForm = function(form) {
              eventFactory.createEvent(angular.copy(form), this.event);
              // $scope.event.push(angular.copy(form));
              console.log($scope.event);
          }
      }])

服务/ eventFactory.js

angular.module('addEvent')
    .factory('eventFactory', function() {
        var eventFactory = {};
        var events = [];
        eventFactory.getAllEvents = function() {
            return events;
        }
        eventFactory.createEvent = function(event, eventList) {
            events.push(event);
            eventList = events;
            return eventList;
        }
        return eventFactory;
    })    

在index.html我以这种方式添加了脚本

<script src="./js/jquery-1.12.4.js"></script>
<script src="./js/bootstrap.js"></script>
<script src="./js/angular.min.js"></script>
<script src="./js/angular-route.js"></script>
<script src="./js/app.js"></script>
<script src="./js/controller.js"></script>
<script src="./services/eventFactory.js"></script>

2 个答案:

答案 0 :(得分:5)

您需要在$rootScope方法

中注入run()
.run(['$rootScope',function($rootScope){
    $rootScope.event=[];
}]);

而不是

.run(['$rootScope',function(){
    $rootScope.event=[];
}]);

答案 1 :(得分:1)

您忘记在$rootScope函数中添加run服务作为参数,这就是您看到错误Uncaught ReferenceError: $rootScope is not defined

的原因

angular
  .module('demo', [])
  .run(run)
  .controller('DefaultController', DefaultController);
  
  run.$inject = ['$rootScope'];
  
  function run($rootScope) {
    $rootScope.events = [];
    console.log($rootScope.events);
  }
  
  function DefaultController() {
    var vm = this;
  }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demo">
  <div ng-controller="DefaultController as ctrl">
  </div>
</div>