为什么foodModule没有定义错误?Angular js

why foodModule not defined error? Angular js

本文关键字:Angular js 错误 定义 foodModule 为什么      更新时间:2023-09-26

嗨,我一直在把它从路由文件中分离出来。但它给出了未定义的模块错误。有人能猜出问题吗?

main.js

var foodModule = angular.module('scratchpad',['ui.router','ngResource']);

route.js

console.log('route.js included successfully');

foodModule.config(function($stateProvider,$httpProvider) {
    $stateProvider.state('home',{
    url:'/home',
    templateUrl:'templates/food.html',
        controller:'addUserController'
  })
  .state('scratchpad',{
        url:'/scratchpad',
        templateUrl:'templates/scratchpad.html',
        controller:'scratchListController'
    })
    .state('addNewScratch',{
        url:'/addNewScratch',
        templateUrl:'templates/addNewScratch.html',
        controller:'addScratchController'
    })
    .state('scratchpad.viewScratch',{
        url:'/scratchpad/:id/view',
        templateUrl:'templates/viewScratch.html',
        controller:'viewScratchController'
    })
}).run(function($state){
    $state.go('home');
});

错误:

Uncaught ReferenceError: foodModule is not defined

不要缓存你的angular模块,你正在将事情泄露到全局范围中。相反:

对于main.js:

//Just declare the module
angular.module('scratchpad',['ui.router','ngResource']);

对于路由js。。。这样做吗:

angular.module('scratchpad')
  .config(function($stateProvider,$httpProvider) {
    $stateProvider.state('home',{
    url:'/home',
    templateUrl:'templates/food.html',
        controller:'addUserController'
  })
  .state('scratchpad',{
        url:'/scratchpad',
        templateUrl:'templates/scratchpad.html',
        controller:'scratchListController'
    })
    .state('addNewScratch',{
        url:'/addNewScratch',
        templateUrl:'templates/addNewScratch.html',
        controller:'addScratchController'
    })
    .state('scratchpad.viewScratch',{
        url:'/scratchpad/:id/view',
        templateUrl:'templates/viewScratch.html',
        controller:'viewScratchController'
    })
}).run(function($state){
    $state.go('home');
});

更好的是,把它们包在IIFE里。

请参阅John Papa的Angular风格指南以获得更好的解释。。。

我建议用大口/咕噜声把它们捆在一起,这样它们的顺序就正确了,可以把它们捆起来吃。除非使用require/system-js之类的模块加载程序,否则不能保证首先执行main js。以前在IE中被类似的东西咬过。也许这篇文章可以揭示这个问题,但没有什么是好的构建系统无法解决的,所以是的。。。

您可能会下这样的订单:-

<script src="route.js"></script>
<script src="main.js"></script>

应该是这样的:-

 <script src="main.js"></script>
    <script src="route.js"></script>