Nil*_*gor 0 javascript jquery angularjs ngroute angularjs-rootscope
我正在尝试运行并收到以下消息:
未捕获的ReferenceError:在app.js第12行中未定义$ rootScope
这是我的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 = [];
}]);
Run Code Online (Sandbox Code Playgroud)
这个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);
}
}])
Run Code Online (Sandbox Code Playgroud)
服务/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;
})
Run Code Online (Sandbox Code Playgroud)
在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>
Run Code Online (Sandbox Code Playgroud)
你需要注入$rootScope的run()方法
.run(['$rootScope',function($rootScope){
$rootScope.event=[];
}]);
Run Code Online (Sandbox Code Playgroud)
代替
.run(['$rootScope',function(){
$rootScope.event=[];
}]);
Run Code Online (Sandbox Code Playgroud)