有人可以为 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屋!