【问题标题】:Using angularJS with requireJS将 angularJS 与 requireJS 一起使用
【发布时间】:2014-10-06 22:18:11
【问题描述】:

我正在尝试使用 requireJS 加载 angularJS。但是我总是遇到这个错误:

未捕获的错误:[$injector:modulerr] http://errors.angularjs.org/1.2.21/$injector/modulerr?p0=phoneApp&p1=Error%….org%2F1.2.21%2F%24injector%2Fnomod%3Fp0%3DphoneApp%0A%20%20% 20%20at%20Err......7)

我检查了我的代码很多次,所有脚本都正确加载了,但对这个错误一无所知。以下是我的代码:

  1. index.html:
<body ng-app="phoneApp">
    <div class="container" ng-controller="PhoneListCtrl">
        <ul>
            <li ng-repeat="phone in phones">{{phone.name}}</li>
        </ul>
    </div>
</body>
<script src="bower_components/requirejs/require.js" data-main="scripts/main"></script>
  1. main.js
require.config({
    paths : {
        jquery : '../bower_components/jquery/jquery.min',
        angular : '../bower_components/angular/angular.min'
    },
    shim : {
        angular : {
            exports : 'angular'
        }
    }
});

require(['jquery', 'angular'],function($, angular){
    angular.module('phoneApp', [])
    .controller('PhoneListCtrl', function($scope){
        $scope.phones = [
            {'name': 'Nexus S',
             'snippet': 'Fast just got faster with Nexus S.'},
            {'name': 'Motorola XOOM™ with Wi-Fi',
             'snippet': 'The Next, Next Generation tablet.'},
            {'name': 'MOTOROLA XOOM™',
             'snippet': 'The Next, Next Generation tablet.'}
        ];
    });
});

【问题讨论】:

  • 您可以尝试在 html `' 中移动您的 &lt;script&gt; 标记吗?
  • shim for angular中,您还应该在exports之前指定deps: ['jquery'],

标签: angularjs requirejs


【解决方案1】:

发生的情况是 HTML 在您的脚本注册用于引导您的应用程序的模块之前加载。为了使 RequireJS 与 AngularJS 代码一起工作,需要手动引导您的应用程序。为此,请执行以下操作:

  1. body 标记中删除ng-app 属性
  2. 使用控制器定义模块后,像这样手动引导您的应用程序angular.bootstrap(document, ["phoneApp"])

请记住,您也可以重用其他模块的 AngularJS 实现,请查看我对这个问题的回答:Does it make sense to use Require.js with Angular.js?

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-20
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 2015-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多