2016-08-23 5 views
0

하나의 각 구성 요소 컨트롤러 내에서 다른 구성 요소 컨트롤러로 함수를 호출하려고합니다. 내가 this 답을 찾았지만 컨트롤러는 내가 따라 한 튜토리얼에 표시된 것과 다르게 정의되었으므로 구성 요소와 템플릿을 어떻게 참조해야하는지 혼란 스럽다. 여기각도 컨트롤러 및 구성 요소 정의

내가 현재 공식 각 튜토리얼을 기반으로 내 컨트롤러 중 하나를 정의하는 방법이다

angular. 
    module('moduleName'). 
    component('firstComponent', { 
    templateUrl: 'url/to/template', 
    controller: function FirstController($scope) { 
     //I want to call a function in SecondController here 
    } 
    }); 

//in another component file 
angular. 
    module('moduleName'). 
    component('secondComponent', { 
    templateUrl: 'url/to/template', 
    controller: function SecondController($scope) { 
     //function here which will be called 
    } 
    }); 

... 난이 예에서 나는 위의 링크처럼 구조를 다시 말

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

app.controller('One', ['$scope', '$rootScope' 
    function($scope) { 
     $rootScope.$on("CallParentMethod", function(){ 
      $scope.parentmethod(); 
     }); 

     $scope.parentmethod = function() { 
      // task 
     } 
    } 
]); 

//in another file 
var app= angular.module("myApp",[]); 
app.controller('two', ['$scope', '$rootScope' 
    function($scope) { 
     $scope.childmethod = function() { 
      $rootScope.$emit("CallParentMethod", {}); 
     } 
    } 
]); 

각 컨트롤러의 구성 요소와 각 템플릿을 참조하려면 어떻게해야합니까? 나는 위에 링크 된 예제 에서처럼 그들을 쓰려고했지만 아무 일도 없었습니다. 나는 어떤 오류도 내지 않았지만 말 그대로 아무 일도 일어나지 않았습니다. 페이지에 아무 것도 표시되지 않았습니다. 그것은 콘솔에 쓰려고했지만 아무 것도 나타나지 않았습니다.

+0

당신은 또한 당신의 HTML을 추가 할 수 있습니까? – Aravind

+0

현재로서는 HTML이 없습니다. 콘솔 로깅과 함께 테스트 할 알림 기능을 추가했습니다. 콘솔 로그 ("재구성"이전)를 사용했을 때 메시지가 나타났습니다. 구조 조정을 시도한 후에 아무 일도 없었습니다. 나는 컨트롤러가 서로 "이야기"하기를 원할뿐입니다. 그 문제에 대해서는 스스로 말하려합니다. – user1852176

답변

1

두 번째 코드 블록은 올바른 개념이지만 두 컨트롤러 모두 작동하도록 인스턴스화해야합니다.

다음은 작동하는 JSFiddle입니다. https://jsfiddle.net/reid_horton/rctx6o1g/

단추를 클릭하면 텍스트 아래에 Hello from callerComponent! 텍스트가 나타납니다.

HTML

<div ng-app="myApp"> 
    <caller-component></caller-component> 
    <callee-component><</callee-component> 
</div> 

JS는

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

app.component("callerComponent", { 
    template: "<button ng-click='externalCall()'>Click Me!</button>", 
    controller: function ($scope, $rootScope) { 
     $scope.externalCall = function() { 
      $rootScope.$emit("setText"); 
     } 
    } 
}); 

app.component("calleeComponent", { 
    template: "<p>{{ myText }}</p>", 
    controller: function ($scope, $rootScope) { 
     $rootScope.$on("setText", function() { 
      $scope.myText = "Hello from callerComponent!" 
     }); 
    } 
}); 
+0

감사합니다. 내가 혼란스러워하는 유일한 것은 컨트롤러의 이름입니다. 명시 적으로 선언되지 않았으므로 Angular는 컨트롤러의 이름이 해당 구성 요소와 동일하다고 가정합니까? – user1852176

+0

컨트롤러 기능 자체는 익명이므로 이름이 없습니다. 구성 요소 템플릿에서 컨트롤러에 액세스해야하는 경우 'controllerAs' 속성을 사용할 수 있습니다. 여기에 대한 자세한 내용 - https://docs.angularjs.org/api/ng/service/$compile#-controlleras- –