从另一个控制器 Angular Js 调用函数 [英] Call function from another Controller Angular Js
问题描述
我是使用 angular js 的新手,我已经声明了许多控制器,现在我想将一个控制器的用户功能转换为另一个控制器.这是我的示例代码.
I am new to using angular js and i have declare many controller and now i want to user function of one controller into another controller. here is my sample code.
app.controller('Controller1',function($scope,$http,$compile){
$scope.test1=function($scope)
{
alert("test1");
}
});
app.controller('Controller2',function($scope,$http,$compile){
$scope.test2=function($scope)
{
alert("test1");
}
});
app.controller('Controller3',function($scope,$http,$compile){
///
});
现在我想在控制器 3 中调用 test2 函数.有没有人可以帮忙..感谢 Avance... :)
Now i want to call test2 function inside controller3. Can anybody help.. Thanks in Avance... :)
推荐答案
您不能从控制器内的控制器调用方法.您将需要提取该方法,创建一个服务并调用它.这也将使代码彼此解耦并使其更具可测试性
You can't call a method from a controller within a controller. You will need to extract the method out, create a service and call it. This will also decouple the code from each other and make it more testable
(function() {
angular.module('app', [])
.service('svc', function() {
var svc = {};
svc.method = function() {
alert(1);
}
return svc;
})
.controller('ctrl', [
'$scope', 'svc', function($scope, svc) {
svc.method();
}
]);
})();
示例:http://plnkr.co/edit/FQnthYpxgxAiIJYa69hu?p=preview
这篇关于从另一个控制器 Angular Js 调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!