• angularJs中$controller的使用



    $controller的使用

    参考: https://stackoverflow.com/questions/27866620/can-someone-provide-a-use-case-for-the-controller-service-in-angularjs

    You can create common functions which are to be executed on $scope into one controller may be named 'CommonCtrl'.

    angular.module('app',[]).controller('CommonCtrl', ['$scope', function($scope){
          var self = this;
          $scope.stuff1 = function(){
    
          }
    
          $scope.stuff2 = function(){
    
          }
          self.doCommonStuff = function(){
                   // common stuff here
                   $scope.stuff1();
                   $scope.stuff2();
    
          };
          return self;
    }]);

    And inject this controller in other controllers let say 'TestCtrl1' like

    angular.module('app',[]).controller('TestCtrl1', ['$scope','$controller', function($scope, $controller){
            var commonCtrl = $controller('CommonCtrl',{$scope: $scope}); // passing current scope to commmon controller
            commonCtrl.doCommonStuff();
    }]);

    Here, the in second argument of $controller service, we are passing dependencies that are required by CommonCtrl. So the doCommonStuff method will use TestCtrl1 controller's scope.

    -----------------------------------------------------------------------------

    To mention one, it is useful in creating the target controller during unit testing.

    Lets say you have a controller with signature .controller('MainCtrl', function($scope, serviceA){..}).

    In testing,

    // ...
    
    beforeEach(inject(function ($rootScope, $controller, serviceA) {
    
      // assign injected values to test module variables
      scope = $rootScope.$new();
      service = serviceA
    
      // create the controller, by passing test module variables values as dependencies
      $controller('MainCtrl', {'$scope': scope, 'serviceA': service});
    }));
    
    it('test on controller', function() {
      //...
    });
  • 相关阅读:
    C常见问题
    费曼学习法
    结构体组包和指针函数的函数指针
    C中拼接和解析字符串函数
    隧道协议
    并发Queue
    并发包阻塞队列之ArrayBlockingQueue
    springboot集成freemarker 配置application.properties详解
    springmvc常用注解标签详解
    tomcat优化
  • 原文地址:https://www.cnblogs.com/oxspirt/p/10524012.html
Copyright © 2020-2023  润新知