program tip

angularJS : 부모 범위에서 자식 범위 함수를 호출하는 방법

radiobox 2020. 9. 1. 07:24
반응형

angularJS : 부모 범위에서 자식 범위 함수를 호출하는 방법


부모 범위에서 자식 범위에 정의 된 메서드를 어떻게 호출 할 수 있습니까?

function ParentCntl() {
    // I want to call the $scope.get here
}

function ChildCntl($scope) {
    $scope.get = function() {
        return "LOL";    
    }
}

http://jsfiddle.net/wUPdW/


$broadcast부모에서 자식으로 사용할 수 있습니다 .

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/

업데이트 : 덜 결합되고 더 테스트 가능한 다른 버전이 있습니다.

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/


다른 해결책을 제안하겠습니다.

var app = angular.module("myNoteApp", []);


app.controller("ParentCntl", function($scope) {
    $scope.obj = {};
});

app.controller("ChildCntl", function($scope) {
    $scope.obj.get = function() {
            return "LOL";    
    };
});

적은 코드와 프로토 타입 상속을 사용합니다.

별안간 밀다


자녀가 초기화 할 때 부모에 자녀의 기능을 등록합니다. 템플릿에서 명확성을 위해 "as"표기법을 사용했습니다.

주형

<div ng-controller="ParentCntl as p">
  <div ng-controller="ChildCntl as c" ng-init="p.init(c.get)"></div>
</div>

컨트롤러

...
function ParentCntl() {
  var p = this;
  p.init = function(fnToRegister) {
    p.childGet = fnToRegister;
  };
 // call p.childGet when you want
}

function ChildCntl() {
  var c = this;
  c.get = function() {
    return "LOL";    
  };
}

"하지만", 당신은 " ng-init 이 방법으로 사용하면 안된다 !"라고 말합니다. 네,하지만

  1. 그 문서는 이유를 설명하지 않습니다.
  2. I don't believe the documentation authors considered ALL possible use cases for it.

I say this is a good use for it. If you want to downvote me, please comment with reasons! :)

I like this approach because it keeps the components more modular. The only bindings are in the template, and means that

  • the child Controller doesn't have to know anything about which object to add its function to (as in @canttouchit's answer)
  • the parent control can be used with any other child control which has a get function
  • doesn't require broadcasting, which will get very ugly in a big app unless you tightly control the event namespace

This approach more closely approaches Tero's idea of modularising with directives (note that in his modularised example, contestants is passed from parent to "child" directive IN THE TEMPLATE).

Indeed another solution might be to consider implementing the ChildCntl as a directive and use the & binding to register the init method.


You can make child object.

var app = angular.module("myApp", []);


app.controller("ParentCntl", function($scope) {
    $scope.child= {};
    $scope.get = function(){
      return $scope.child.get(); // you can call it. it will return 'LOL'
    }
   // or  you can call it directly like $scope.child.get() once it loaded.
});

app.controller("ChildCntl", function($scope) {
    $scope.obj.get = function() {
            return "LOL";    
    };
});

Here child is proving destination of get method.

참고URL : https://stackoverflow.com/questions/19038778/angularjs-how-to-call-child-scope-function-in-parent-scope

반응형