有人可以为AngularJS中的$ controller服务提供用例吗? [英] Can someone provide a use case for the $controller service in AngularJS?
问题描述
Angularjs文档提供$ controller服务的用法如下:
$controller(constructor, locals);
Angularjs docs give the usage of $controller service as:
$controller(constructor, locals);
任何人都可以将重点放在这两个方面吗?
Can anyone focus some light on these 2 points:
- 何时使用 $ controller 服务.请提供一些用例.
- 有关传递给它的"locals"参数的详细信息.
- When to use $controller service. Please provide some use case.
- Details about 'locals' parameter passed to it.
推荐答案
您可以创建将在$ scope上执行到一个控制器中的通用功能,该功能可能命名为'CommonCtrl'
.
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;
}]);
然后将此控制器注入其他控制器中,让我们说'TestCtrl1'之类的
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();
}]);
这里,在$ controller服务的第二个参数中,我们正在传递CommonCtrl所需的依赖项.因此,doCommonStuff方法将使用TestCtrl1控制器的作用域.
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.
这篇关于有人可以为AngularJS中的$ controller服务提供用例吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!