angularJS: How to call child scope function in parent scope

前端 未结 4 2012
难免孤独
难免孤独 2020-11-28 03:41

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($         


        
4条回答
  •  忘掉有多难
    2020-11-28 04:22

    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";    
        }
    }
    

    Working fiddle: 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";    
        }
    }
    

    Fiddle: http://jsfiddle.net/uypo360u/

提交回复
热议问题