angularJS:如何调用子作用域功能父范围 [英] angularJS: How to call child scope function in parent scope

查看:166
本文介绍了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";    
    }
}

http://jsfiddle.net/wUPdW/

推荐答案

您可以使用 $广播 从父到子:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆