How to write testable controllers with private methods in AngularJs?

前端 未结 4 1369
遇见更好的自我
遇见更好的自我 2020-12-12 14:28

Alright, so I have been stumbling upon some issue for a long time and I would like to hear an opinion from the rest of community.

First, let\'s look at some abstract

4条回答
  •  情深已故
    2020-12-12 15:03

    The controller function you provided will be used by Angular as a constructor; at some point it will be called with new to create the actual controller instance. If you really need to have functions in your controller object that are not exposed to the $scope but are available for spying/stubbing/mocking you could attach them to this.

    function Ctrl($scope, anyService) {
    
      $scope.field = "field";
      $scope.whenClicked = function() {
        util();
      };
    
      this.util = function() {
        anyService.doSmth();
      }
    }
    

    When you now call var ctrl = new Ctrl(...) or use the Angular $controller service to retrieve the Ctrl instance, the object returned will contain the util function.

    You can see this approach here: http://jsfiddle.net/yianisn/8P9Mv/

提交回复
热议问题