I'm using ui-router to display 2 ui-views, one within the other. They are organized like this:
.state('itemAbstract', {
url: '/items',
abstract: true,
templateUrl: 'client/views/item.ng.html',
controller: 'moveCtrl',
})
.state('item', {
url: "/:itemId",
parent: "itemsAbstract",
views: {
"otherpage":{
templateUrl: 'client/views/other-page.ng.html',
controller: 'otherPageCtrl'
}
}
})
I run the folloowwing in the otherpage
controller when an item is clicked.
$rootScope.$broadcast("somethingClicked",obj)
I try to listen for the event in the item
controller:
$scope.$on("somethingClicked",function(a,b){
console.log(a)
console.log(b);
})
Unfortunately, this function never gets called. I tried putting this listener function in the otherpage
controller, and it was called correctly when the event happened. For some reason, though, this broadcast isn't getting transferred across scopes. That was the whole reason I was using this, to trigger an action in the parent when something in the parent is clicked. Any ideas on why this is not working?
Here is my controller for the item
angular.module('mm').controller('itemCtrl',
function($scope, $meteor, $rootScope, $state, $stateParams) {
var s = $scope;
s.rs = $rootScope;
$scope.$on("somethingClicked",function(a,b){
console.log("there as a click")
console.log(a)
console.log(b);
})
}
I used Batarang to debug and found that despite this code, $scope is not even registering an event listener . $scope.$$listeners
does not have a listener for the somethingClicked event. Very strange, and it doesn't make sense why this isn't working.
Maybe you have independent controllers with no inheritance applied. Inheritance on $scope is declared simply by nesting the controllers on your view. In that case you may use $rootscope to broadcast or listen to event as:
//ctrl1
$rootScope.$broadcast("somethingClicked",obj);
//ctrl2
$rootScope.$on("somethingClicked",function(a,b){
console.log(a)
console.log(b);
});
Take a look at this simple demo as well as an older question on Stack Overflow.
EDITED Based on your sample code I had no problem at all communicating using $rootscope
.
The state declaration use an abstract parent controller and a fetched child controller mapped into the view as:
$stateProvider
.state('test', {
url: '/test',
controller: 'pctrl',
views: {
'main': {
template: '<div ng-controller="pctrl">{{test}}</div>' +
'<div ui-view="childview"></div>'
}
}
})
.state('test.child', {
url: '/test/child',
controller: 'cctrl',
views: {
'childview': {
template: '<div ng-controller="cctrl" />'
}
}
});
Here is a full working demo
Answer found - I had misconfigured my routes file, and had the wrong controller specified for the page I was loading. That's why none of my event listeners registered!
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.