Globally defined AngularJS controllers and encapsulation

旧城冷巷雨未停 提交于 2019-11-27 07:35:50

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.

user1

You can register a controller as part of a module, as answered by pkozlowski-opensource.

If you need minification you can simply extend this by providing the variable names before the actual function in a list:

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

    $scope.phones = [..];
    $scope.orderProp = 'age';
  }]);

This will work the same after "minification":

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

    s.phones = [..];
    s.orderProp = 'age';
  }]);

This notation can be found under "Inline Annotation" at Dependency Injection.

To test a controller, that has been registered as part of a module, you have to ask angular to create your controller. For example:

describe('PhoneListCtrl test', function() {
  var scope;
  var ctrl;

  beforeEach(function() {
    module('[module name]');
    inject(function($rootScope, $controller) {
      scope = $rootScope.$new();
      ctrl = $controller('[module name]', {$scope: scope});
    });
  });

  it('should be ordered by age', function() {
    expect(scope.orderProp).toBe('age');
  });

});

This method of testing the controller can be found under "Testing Controllers" at Understanding the Controller Component.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!