angularjs - 在匿名函数中包装 Controller

标签 angularjs

我是否这样做:

(function () {
'use strict';

// Create the module and define its dependencies.
var app = angular.module('app', [
    // Angular modules 
    'ngAnimate',        // animations
    'ngRoute'           // routing

    // Custom modules 

    // 3rd Party Modules

]);

// Execute bootstrapping code and any dependencies.
app.run(['$log',
    function ($log) {
        $log.log('we are loaded');
    }]);
})();

或者
'use strict';

// Create the module and define its dependencies.
var app = angular.module('app', [
    // Angular modules 
    'ngAnimate',        // animations
    'ngRoute'           // routing

    // Custom modules 

    // 3rd Party Modules

]);

// Execute bootstrapping code and any dependencies.
app.run(['$log',
    function ($log) {
        $log.log('we are loaded');
    }]);

两者似乎都有效 - 有什么区别?

我希望能解释什么是匿名函数,什么时候使用匿名函数,以及为什么我看到 Controller 以两种方式为 AngularJs 编写。

谢谢!

最佳答案

JavaScript 的局部变量只存在于函数范围内!

因此,如果您使用 IIFE(立即调用函数表达式),如下所示:

(function () {
   var app = angular.module('app', []);
})();

您无法在函数之外访问您的模块:
(function () {
   var app = angular.module('app', []);
})();

// will get app is undefined error
app.run(['$log', function ($log) {
    $log.log('we are loaded');
}]);

声明局部变量而不是全局变量是个好主意。这将使您的 app 变量无法在全局环境中访问。

如果你声明一个全局变量,
您的变量可以在任何地方使用,并且可能与其他 javascript 程序发生冲突。

关于angularjs - 在匿名函数中包装 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21445817/

相关文章:

angularjs - sails 无法从 Angular 标签后的请求中读取 GET 参数

javascript - Angular : What is the best way to bind to a global event in a directive

javascript - AngularJS javascript 和 css 打包器

javascript - 无法将数据从 Angular.js 发布到 Node.js

javascript - 在 javascript 中读取本地 xls/xlsx 文件

javascript - 将参数传递给状态导致元素不显示

search - angularJS 搜索模型

javascript - 按增量按索引切片

angularjs - 我如何以 Angular 动态显示我的 Flash 消息。消息必须来自 API 响应

angularjs - Angular 1.4 View 封装和 Shadow DOM - 有可能吗?