Globally defined AngularJS controllers and encapsulation

前端 未结 2 1802
说谎
说谎 2020-12-01 07:42

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

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

Do the controller fu

2条回答
  •  渐次进展
    2020-12-01 08:17

    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.

提交回复
热议问题