我需要在 AngularJS 的另一个 Controller 中调用函数。我怎样才能做到这一点?
代码:
app.controller('One', ['$scope',
function($scope) {
$scope.parentmethod = function() {
// task
}
}
]);
app.controller('two', ['$scope',
function($scope) {
$scope.childmethod = function() {
// Here i want to call parentmethod of One controller
}
}
]);
最佳答案
Controller 之间的通信是通过 $emit
+ $on
/$broadcast
+ $on
方法完成的。
因此,在您的情况下,您想在 Controller “二”内调用 Controller “一”的方法,正确的方法是:
app.controller('One', ['$scope', '$rootScope'
function($scope) {
$rootScope.$on("CallParentMethod", function(){
$scope.parentmethod();
});
$scope.parentmethod = function() {
// task
}
}
]);
app.controller('two', ['$scope', '$rootScope'
function($scope) {
$scope.childmethod = function() {
$rootScope.$emit("CallParentMethod", {});
}
}
]);
当调用$rootScope.$emit
时,您可以发送任何数据作为第二个参数。
关于angularjs - 如何从 AngularJS 中的另一个 Controller 调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29467339/