angularJS:如何在父作用域中调用子作用域函数 [英] angularJS: How to call child scope function in parent scope
本文介绍了angularJS:如何在父作用域中调用子作用域函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从父作用域调用子作用域中定义的方法?
How can call a method defined in child scope from its parent scope?
function ParentCntl() {
// I want to call the $scope.get here
}
function ChildCntl($scope) {
$scope.get = function() {
return "LOL";
}
}
推荐答案
您可以使用 $broadcast
从父级到子级:
You can use $broadcast
from the parent to a child:
function ParentCntl($scope) {
$scope.msg = "";
$scope.get = function(){
$scope.$broadcast ('someEvent');
return $scope.msg;
}
}
function ChildCntl($scope) {
$scope.$on('someEvent', function(e) {
$scope.$parent.msg = $scope.get();
});
$scope.get = function(){
return "LOL";
}
}
工作小提琴:http://jsfiddle.net/wUPdW/2/
更新:还有另一个版本,耦合更少,可测试性更强:
UPDATE: There is another version, less coupled and more testable:
function ParentCntl($scope) {
$scope.msg = "";
$scope.get = function(){
$scope.$broadcast ('someEvent');
return $scope.msg;
}
$scope.$on('pingBack', function(e,data) {
$scope.msg = data;
});
}
function ChildCntl($scope) {
$scope.$on('someEvent', function(e) {
$scope.$emit("pingBack", $scope.get());
});
$scope.get = function(){
return "LOL";
}
}
小提琴:http://jsfiddle.net/uypo360u/
这篇关于angularJS:如何在父作用域中调用子作用域函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文