gpt4 book ai didi

javascript - 使用 $scope.$emit() 在组件之间传递数据

转载 作者:行者123 更新时间:2023-11-30 20:44:51 29 4
gpt4 key购买 nike

我试图在具有相同父组件的两个组件之间传递数据(简单版本:我有 child1 组件、child2 组件,它们都是父组件的子组件)。此外,所有组件都作为 Controller 。

父组件也是根组件(它没有任何父组件)所以我想我必须使用 $rootScope

如果我想将 var myVar(整数)从 child1 传递给 child2,我想我应该这样做:

在 child1 组件中:

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

在父组件中:

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

在 child2 组件中:

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

我是新手,不明白为什么这行不通,可能没什么大不了的,如果有人能帮助我,我将不胜感激:) ty!

顺便说一下,我在两个控制台日志中都得到了“未定义”,但是 myVar 在 child1 中被正确定义了。

最佳答案

你需要广播给 child 的 parent :

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

$scope.$broadcast 将消息向下发送到链中,但是如果您向范围的父级广播,则父级将向下发送消息,其中包括两个 兄弟.

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>

关于javascript - 使用 $scope.$emit() 在组件之间传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48830278/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com