programing

Angular 1.5, 부모 컨트롤러에서 컴포넌트의 함수를 호출합니다.

codeshow 2023. 4. 2. 11:41
반응형

Angular 1.5, 부모 컨트롤러에서 컴포넌트의 함수를 호출합니다.

각도 1.5 컴포넌트를 사용하면 컴포넌트에서 부모에게 콜백할 수 있습니다.부모 컨트롤러의 함수에서 컴포넌트 내의 함수를 호출할 수 있는 방법이 있습니까?

내 컴포넌트는 태스크러너라고 불리며, 아래는 부모 컨테이너에 있는 컴포넌트의 HTML입니다.

<task-runner taskcategogyid=5></task-runner>

 <button type="button" ng-click="doSomethingInParent()">ParentToChildButton</button>

플렁커가 왔어요.ParentToChildButton을 클릭하면 doSomethingInParent() 함수가 컴포넌트의 remotefunc를 호출합니다.

몇 가지 다른 방법:

  1. 양방향 바인딩이 있는 속성으로 개체를 전달합니다( ).scope:{myattr:'='}task-item-interruptive에 대한 명령어입니다.이 명령어는 부모 컨트롤러가 호출할 함수를 추가할 수 있습니다.
  2. 단방향 바인딩을 가진 Atribute를 설정합니다( ).scope:{myattr:'@'})에 기입해 주세요.attrs.$observe액션을 트리거하기 위한 변경 또는 양방향 바인딩(scope:{myattr:'='})을 클릭합니다.$scope.$watch액션을 트리거하기 위해 변경합니다.
  3. 지시로 이벤트를 발생시킵니다(scope:{raiseLoaded:'&onLoaded'}리모트 컨트롤 오브젝트를 나타내는 오브젝트를 원하는 액션을 트리거하는 메서드와 함께 전달합니다.이벤트를 진행하기 위해 전화를 걸면raiseLoaded({remoteControl: remoteControlObj})그리고 나서 그 사건을 듣기 위해<task-item-header on-loaded="setRemote(remoteControl)">를 가지고 있다고 가정하면setRemote()메서드를 지정합니다.

업데이트 방금 당신의 질문이 AngularJS의 새로운 버전에 대한 것임을 깨달았습니다.그래서 제 답변이 아직 적용되는지 잘 모르겠습니다.일단은 여기에 두겠습니다만, 도움이 되지 않는다고 판단되면 삭제할 수 있습니다.

예전에는 이런 것이 필요했기 때문에 이 문제를 어떻게 해결했는지 공유하려고 합니다.

OP와 마찬가지로 부모 컴포넌트에서 자녀 컴포넌트의 메서드를 자유롭게 트리거해야 했습니다.$onChanges 라이프 사이클 훅을 사용하지 않고 부모에서 이 메서드를 자유롭게/별도로 트리거할 수 있기를 원했습니다.

대신 알림 등록 메커니즘을 생성하여 하위 구성 요소가 로드될 때 부모에 메서드를 '등록'할 수 있도록 했습니다.이 메서드는 $onChanges 사이클 외부에 있는 부모에 의해 자유롭게 트리거될 수 있습니다.

나는 이것을 증명하기 위해 코데펜을 만들었다.데이터 변경과 관련이 없는 상위 유형의 통지를 처리하도록 쉽게 확장할 수 있습니다.

Index.html

<div ng-app="tester">
  <parent></parent>
</div>

스크립트.js

angular.module('tester', []);

angular.module('tester').component('parent', {
  controller: parentController,
  template: `
    <div class="tester-style">
      <button ng-click="$ctrl.notifyChild()">Notify child</button>
      <child parent-to-child-notification-registration="$ctrl.childComponentNotificationRegistration(handler)">
    </div>
  `
});

function parentController() {
  let childComponentEventHandler = null;

  this.$onInit = function() {
    this.value = 0;
  };

  this.childComponentNotificationRegistration = function(handler) {
    childComponentEventHandler = handler;
    console.log('Child component registered.');
  };

  this.notifyChild = function() {
    if (childComponentEventHandler) {
      childComponentEventHandler(this.value++);
    }
  };
}

angular.module('tester').component('child', {
  bindings: {
    parentToChildNotificationRegistration: '&',
  },
  controller: childController,
  template: `
    <div class="tester-style">
      <h4>Child Component</h4>
    </div>
  `
});

function childController() {
  this.$onInit = function() {
    this.parentToChildNotificationRegistration({
      handler: this.processParentNotification
    });
  };

  this.processParentNotification= function(parentValue) {
    console.log('Parent triggered child notification handler!!!');
    console.log('Value passed to handler:', parentValue);
  };
};

}

, @adam0101의 #3 의 답변과 같은 것에 대해서는, 코데펜을 참조해 주세요.

언급URL : https://stackoverflow.com/questions/37215547/angular-1-5-calling-a-function-in-a-component-from-parent-controller

반응형