Globally defined AngularJS controllers and encapsulation

前端 未结 2 1818
说谎
说谎 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:27

    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.

提交回复
热议问题