Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
398 views
in Technique[技术] by (71.8m points)

javascript - Globally defined AngularJS controllers and encapsulation

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

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

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();

Rather than this:

    functionName();

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...