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() { //... });

转载于:https://www.cnblogs.com/oxspirt/p/10524012.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值