0

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

未捕获的 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>
4

2 回答 2

6

您需要$rootScoperun()方法中注入

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

代替

.run(['$rootScope',function(){
    $rootScope.event=[];
}]);
于 2016-10-10T05:25:27.457 回答
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>

于 2016-10-10T05:42:36.460 回答