[英]send data to another controller with $emit
在我的角度應用程序中,我有多個controllers
,我需要將數據從一個controller
發送到另一個controller
,所以我使用$scope.$emit
來傳輸數據,但不幸的是它無法正常工作。
var app = angular.module('tApp', []); app.controller('masterpage', function($scope) { $scope.masterpagescope = 'A'; }); app.controller('subpage', function($scope) { $scope.subpagescope = ['data1', 'data2', 'data2+n']; $scope.sendData = function() { $scope.$emit('send-data', $scope.masterpagescope, $scope.subpagescope); console.log($scope.masterpagescope); } $scope.sendData(); });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="tApp"> <div ng-controller="masterpage" id="masterpage"> {{masterpagescope}} <div ng-controller="subpage" id="subpage"> {{subpagescope}} </div> </div> </div>
在上面的代碼段中,我試圖將$scope.subpagescope
的數據發送到$scope.masterpagescope
您需要使用$ on來監聽母版控制器中的$ emit
app.controller('masterpage', function($scope) {
$scope.masterpagescope = 'A';
$scope.$on('send-data', function(event, data) {
$scope.masterpagescope = data;
});
});
app.controller('subpage', function($scope) {
$scope.subpagescope = ['data1', 'data2', 'data2+n'];
$scope.sendData = function() {
$scope.$emit('send-data', $scope.subpagescope);
}
$scope.sendData();
});
推薦此文章的主題
您尚未在父控制器中訂閱事件。
$scope.$on('send-data', function(event, data){
//do whatever with data here...
});
同樣,在發射時,將所有數據封裝在一個對象中:
$scope.$emit('send-data', {master: $scope.masterpagescope, sub : $scope.subpagescope});
PS:存儲$ on返回的值,該值是用於事件訂閱的注銷功能。 在頁面的“銷毀”上調用存儲的函數。
其他答案建議您應該有$scope.$on
。
$scope.$on('send-data', function() { ... })
但是我強烈建議不要使用$emit
/ $broadcast
在控制器之間共享數據。 通用的Angular服務會更好。
更新:為什么我不建議使用$emit
/ $broadcast
?
對於初學者來說, $emit
/ $broadcast
用法有些復雜。 您可以在Angular范圍樹中向上$emit
,向下$broadcast
。 如果需要與同級(同級)范圍進行通信,則需要先在父范圍內進行$emit
然后$broadcast
[或使用$rootScope
? -注意神物反模式]。
每個$scope.$on
都會注冊一個事件監聽器。 過多使用它可能會導致內存泄漏。 當然,您可以相應地殺死事件偵聽器(要做的其他工作)。
如果$emit
/ $broadcast
/ $scope.$on
周圍太多,代碼可能會變得有些混亂。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.