我问的是因为我在$ state.go语句之后发现如果在目标页面的控制器中使用$ scope.emit,则初始页面的控制器$ state。$ on无法接收有时消息。
无论如何,我注意到每个控制器都没有发生这种行为,所以这让我感到困惑。
以我的项目中的3个控制器为例,Ctrl1和Ctrl2都有一个state.go到Ctrl3。
CTRL1:
var NewsCtrl = function($rootScope, $scope, $http, $q, $location, $state, $stateParams, $sce, $ionicHistory, $ionicViewService) {
$rootScope.$on('updateNewsLocalViewsCount', function(event, data) {
console.log('##root scope receiving updateNewsLocalViewsCount:' + event + ':' + JSON.stringify(data));
});
$scope.$on('updateNewsLocalViewsCount', function(event, data) {
console.log('#scope receiving updateNewsLocalViewsCount:' + event + ':' + JSON.stringify(data));
});
$scope.gotoNotifications = function() {
$state.go("app.notifications");
};
};

<button
class="button-icon"
ng-click="gotoNotifications()">notifications
</button>
&#13;
CTRL2:
var LeadsCtrl = function($cordovaNetwork, $cordovaPreferences, $ionicPlatform, $localStorage, $rootScope,
$cordovaStatusbar, $state, $location, $translate,
$ionicLoading) {
$rootScope.$on('LeadSavedAsCustomer', function(event, data) {
console.log('#root scope receiving Leads Ctrl-LeadSavedAsCustomer-' + event + ':' + JSON.stringify(data) + ' DO NOTHING ');
});
$scope.$on('LeadSavedAsCustomer', function(event, data) {
console.log('#scope receiving Leads Ctrl-LeadSavedAsCustomer-' + event + ':' + JSON.stringify(data) + ' DO NOTHING ');
});
$scope.gotoNotifications = function() {
$state.go("app.notifications");
};
};
&#13;
<button
class="button-icon"
ng-click="gotoNotifications()">
notifications
</button>
&#13;
CTRL3:
var NotificationsCtrl = function($scope) {
$scope.$emit('updateNewsLocalViewsCount', {"newsid":"1", "counts":"1"});
$scope.$emit('LeadSavedAsCustomer', {"customerId": "1", "leadId": "1"});
}
&#13;
结果:
Ctrl1中的:仅调用$ rootScope。$ on。
Ctrl2中的:$ rootScope。$ on和$ scope。$ on都被调用。
但实际上这些控制器非常相似。不确定为什么行为不同......
state.go或html会自动建立父/子关系吗?
答案 0 :(得分:0)
在您的HTML中,您的NotificationsCtrl
是LeadsCtrl
吗?在这种情况下,前者将是后者的孩子。它会在$scope.$on
上触发。详细了解Scope Hierarchy in AngularJS
使用ng-controller嵌套控制器会产生正常的原型继承,就像ng-include和ng-switch一样,因此适用相同的技术。如果您真的想通过控制器范围继承来共享数据,那么您无需做任何事情。子作用域可以访问所有父作用域属性。