简体   繁体   中英

pass data between components with $scope.$emit()

I'm trying to pass data between two components that have the same parent component (simple version: I have child1 component, child2 component, and both of them are children of parent component). Also all the components are as controllers.

Parent component is also a root component (it doesnt have any parent components) so I thought I had to use $rootScope ?

If i want to pass a var myVar (integer) from child1 to child2 I guess I should do :

in child1 component:

$rootScope.$emit('myEvent', vm.myVar);

in parent component:

$scope.$on('changeTab', function(){
   console.log('parent', vm.myVar);
});
$scope.$broadcast('changeTab', vm.myVar);

in child2 component:

$rootScope.$on('changeTab', function () {
    console.log('child2', vm.myVar);
});

I am new to this and don't understand why this doesn't work, probably nothing big, if anyone could help me out would appreciate it :) ty !

By the way I get "undefined" in both console logs, but well myVar is defined properly in child1.

You need to broadcast to the child's parent:

$scope.$parent.$broadcast('hi', {
    msg: 'Hello there!'
});

$scope.$broadcast sends the message down the chain, but if you broadcast to the scope's parent then the parent will send the message down, which includes both siblings.

 angular.module('appModule', []) .controller('ParentController', [function() { this.hello = 'I am the parent'; }]) .controller('Child1Controller', ['$scope', function($scope) { this.hello = 'I am Child 1'; var that = this; $scope.$on('hi', function(event, data) { console.log(data.msg); that.hello = data.msg; }); }]) .controller('Child2Controller', ['$scope', function($scope) { this.hello = 'I am Child 2'; this.sayHello = function(str) { $scope.$parent.$broadcast('hi', { msg: str }); } }]); angular.bootstrap(window.document, ['appModule'], { strictDi: true });
 div { border: 1px dotted #f00; padding: 15px; }
 <div ng-controller="ParentController as parentCtrl"> <p>{{parentCtrl.hello}}</p> <div ng-controller="Child1Controller as child1Ctrl"> <p>{{child1Ctrl.hello}}</p> </div> <div ng-controller="Child2Controller as child2Ctrl"> <p>{{child2Ctrl.hello}}</p> <button type="button>" ng-click="child2Ctrl.sayHello('Child 2 is cool')">Say Hello to Child 1</button> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM