全局定义的 AngularJS 控制器和封装 [英] Globally defined AngularJS controllers and encapsulation

查看:23
本文介绍了全局定义的 AngularJS 控制器和封装的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 AngularJS 的教程,控制器函数只是位于全局范围内.

According to AngularJS's tutorial, a controller function just sits within the global scope.

http://docs.angularjs.org/tutorial/step_04

控制器函数本身是否会自动解析为封装的作用域,还是驻留在全局作用域中?我知道他们被传递了对他们自己的 $scope 的引用,但看起来函数本身只是位于全局范围内.显然这可能会导致问题,我通过经验和教育学会了封装 此外,如果它们确实存在于全局范围内,那么将它们封装在像这样被引用的对象中是否不被认为是最佳实践:

Do the controller functions themselves automatically get parsed into an encapsulated scope, or do they dwell within the global scope? I know that they are passed a reference to their own $scope, but it appears that the function themselves are just sitting in the global scope. Obviously this can cause problems down the road, and I have learned through experience and education to encapsulate Further more, if they do dwell within the global scope, would it not be considered a best practice to encapsulate them within an object to be referenced like this:

    Object.functionName();

而不是这个:

    functionName();

为了防止因全局作用域(即覆盖函数等)的污染而出现的问题

So as to prevent issues that occur with the pollution of the global scope (ie overriding functions, etc..)

推荐答案

AngularJS 支持 2 种注册控制器函数的方法——作为全局可访问的函数(你可以在提到的教程中看到这种形式)或作为模块的一部分(形成一种命名空间).更多关于模块的信息可以在这里找到:http://docs.angularjs.org/guide/module 但简而言之,可以像这样在模块中注册一个控制器:

AngularJS supports 2 methods of registering controller functions - either as globally accessible functions (you can see this form in the mentioned tutorial) or as a part of a modules (that forms a kind of namespace). More info on modules can be found here: http://docs.angularjs.org/guide/module but in short one would register a controller in a module like so:

angular.module('[module name]', []).controller('PhoneListCtrl', function($scope) {

  $scope.phones = [..];

  $scope.orderProp = 'age';
});

AngularJS 在许多示例中使用了一种简短的全局函数形式来声明控制器,但是虽然这种形式适用于快速示例,但不应在实际应用中使用.

AngularJS uses a short, global-function form of declaring controllers in many examples but while this form is good for quick samples it rather shouldn't be used in real-life applications.

简而言之:AngularJS 使正确封装控制器功能成为可能,但也暴露了一个更简单、快速的 &将它们声明为全局函数的肮脏方式.

In short: AngularJS makes it possible to properly encapsulate controller functions but also exposes a simpler, quick & dirty way of declaring them as global functions.

这篇关于全局定义的 AngularJS 控制器和封装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆