【问题标题】:Issue while running browserify on a simple angular app在简单的 Angular 应用程序上运行 browserify 时出现问题
【发布时间】:2016-09-25 04:42:33
【问题描述】:

我正在尝试使用 node/npm/browserify 构建我的 Angular 应用程序。 ./app/controllers、./app/directives、./app/services 基本上都有 index.js 文件,而这些文件又需要()这些 js 文件!下面是根 js 文件,即 public/index.js。

require('./app/controllers/');
require('./app/directives/');
require('./app/services/');

var app = angular.module('myApp', ['ngRoute'])

app.config(function($routeProvider) {
    $routeProvider
    .when("/movie/:movieId", {
        template: require('./views/movie.html'),
        controller: 'MovieCtrl as movie'
    })
    .when("/movie/:movieId/scene/:sceneId", {
        template: require('./views/scene.html'),
        controller: 'SceneCtrl as scene'
    });
});

module.exports = app;

现在运行以下命令后,我确实得到了一个 bundle.js,

浏览 public/index.js -o release/bundle.js

但是,bundle.js 中的以下行会抛出错误“Uncaught ReferenceError: app is not defined”

app.controller('MainCtrl', function ($route, $routeParams, $location, MyFactory) {

现在,我假设因为在 index.js 中指定了 var app,它应该可以在 MainCtrl.js 中访问。有人可以建议我如何完成这项工作吗?

----- 添加更多信息 ------ app/controllers/index.js 包含以下代码:-

require('./MainCtrl.js')
require('./MovieCtrl.js')
require('./SceneCtrl.js')

MainCtrl.js 包含以下代码:-

app.controller('MainCtrl', function ($route, $routeParams, $location, MyFactory) {
    //...
})

【问题讨论】:

    标签: angularjs node.js browserify


    【解决方案1】:

    我不知道代码中的行在哪里......从问题中不清楚,但无论如何:

    现在,我假设因为在 index.js 中指定了 var app,它应该可以在 MainCtrl.js 中访问。

    这个假设是错误的。当您实例化您所包含的任何内容时,您需要传入对您需要的任何内容的引用。

    例如..

    var mainCtrl = new MainCtrl(app);
    

    【讨论】:

    • 嗨,布拉德,添加了一些代码,希望能让事情更清楚。基本上在名为“MainCtrl”的主应用程序上注册一个控制器。
    • 请忽略上面的^评论。我有点弄清楚出了什么问题。在下面发布答案。
    【解决方案2】:

    好的,所以我有点明白发生了什么。 var app 是本地的,无法在其他任何地方访问。一旦我将 app 设置为全局范围(这显然是一件可怕的事情!)并在声明 app 后需要文件,它就起作用了。这大多不是正确的做法,但正如我提到的,这是一个非常初步的尝试。

    app = angular.module('myApp', ['ngRoute'])
    
    app.config(function($routeProvider) {
        $routeProvider
        .when("/movie/:movieId", {
            template: require('./views/movie.html'),
            controller: 'MovieCtrl as movie'
        })
        .when("/movie/:movieId/scene/:sceneId", {
            template: require('./views/scene.html'),
            controller: 'SceneCtrl as scene'
        });
    });
    
    require('./app/controllers/');
    require('./app/directives/');
    require('./app/services/');
    

    【讨论】:

    • 你看到我的回答了吗?它为您提供了另一种选择。至少,如果您要使某些东西全球化,请将其放入 globals 中。
    猜你喜欢
    • 2020-10-23
    • 1970-01-01
    • 2014-04-20
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多