user1852176 user1852176 - 3 months ago 13
AngularJS Question

Defining angular controllers and component

I'm trying to call a function from within one angular component's controller to another component's controller. I found this answer, but the controllers are defined differently than what is shown in the tutorials I followed, so I'm confused as to how I'm supposed to reference the components and templates.

Here is how I currently define one of my controllers based on the official angular tutorial

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


Say I re-structure them like in the example I linked above...

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", {});
}
}
]);


How am I supposed to reference each controller's component which they belong to, and their respective templates? I tried to write them like in the example I linked above, but nothing happened. I didn't get any errors, but literally nothing happened. Nothing was displayed on the page. It tried to write to the console, but nothing appeared.

Answer

Your second block of code has the right concept, but both controllers need to be instantiated for it to work.

Here's a working JSFiddle. https://jsfiddle.net/reid_horton/rctx6o1g/

When you click the button, the text Hello from callerComponent! appears below it.

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