好好爱自己!

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() {
  //...
});
posted @   立志做一个好的程序员  阅读(598)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
历史上的今天:
2017-03-13 Data obtained from ping: is it round trip or one way?
2014-03-13 linux 文件系统操作()

不断学习创作,与自己快乐相处

点击右上角即可分享
微信分享提示