Angularjs 文档给出了 $controller 服务的用法:$controller(constructor, locals);
任何人都可以关注以下两点:
最佳答案
您可以将要在 $scope 上执行的通用函数创建到一个 Controller 中,可以命名为 '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;
}]);
并将这个 Controller 注入(inject)其他 Controller 让我们说'TestCtrl1'就像
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 Controller 的作用域。
关于angularjs - 有人可以提供 AngularJS 中 $controller 服务的用例吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27866620/