I want to create an application in angular.
I have the main controller outside the view and specific controller for view.
How can I emit data from Main Controller to View's Controller (Home Controller)?
I want to execute the function in view controller after emit data from the Main Controller.
I've tried to use - $emit
and $on
but in my case it doesn't work.
My code for example: https://jsfiddle.net/32hb3odk/7/
Index.html
<div ng-app="myApp">
<div class="head-part" ng-controller="MainController as main">
<h1>Header</h1>
<input ng-click="main.EmitData()" type="button" value="Emit data to child control" />
<br /> <br />
</div>
<div class="view-part">
<h2>View:
</h2>
<div ng-view></div>
</div>
<script type=text/ng-template id=home.html>
<div>{{home.title}}</div>
</script>
</div>
Javascript:
angular.module('myApp', ['ngRoute'])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/', {
controller: 'HomeController',
controllerAs: 'home',
templateUrl: 'home.html'
})
.otherwise('/');
}]);
angular.module('myApp').controller('HomeController', ['$scope',function ($scope) {
var vm = this;
vm.title = 'Homepage';
$scope.$on('EmitMain', function(){
alert("GetDataFromMainController");
});
}]);
angular.module('myApp').controller('MainController', ['$scope', function ($scope) {
var vm = this;
vm.EmitData = function(){
$scope.$emit('EmitMain');
}
}]);
That's because $emit
goes up the tree. Use $broadcast
instead as it traverses the tree downwards.