从另一个角度控制器JS调用函数 [英] Call function from another Controller Angular Js
问题描述
我是新来的采用了棱角分明的js和我有许多声明控制器和现在我想一个控制器的用户功能到另一个控制器。这里是我的示例code。
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){
///
});
现在我想打电话给内controller3 test2的功能。
任何人都可以帮助..
谢谢维格尔...:)
Now i want to call test2 function inside controller3. Can anybody help.. Thanks in Avance... :)
推荐答案
您不能调用从控制器内的控制器的方法。您将需要提取出来的方法,创建一个服务并调用它。这也将彼此分离的code,并使其更容易测试
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();
}
]);
})();
例如:<一href=\"http://plnkr.co/edit/FQnthYpxgxAiIJYa69hu?p=$p$pview\">http://plnkr.co/edit/FQnthYpxgxAiIJYa69hu?p=$p$pview
这篇关于从另一个角度控制器JS调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!