I use $broadcast and $on in Angular to jump to the page and transfer data, but the data cannot be received after the jump (it will only be displayed when the button is clicked again)
Specific requirements: click the button on the first page, Pass an array (the shopList array in the picture below) to the second page so that the second page can receive the shopList array
First page
<a ui-sref="app.checkOut" ng-click="checkoutShop(shopList)"><b>结算</b></a>
Corresponding controller (main controller-parent)
$rootScope.checkoutShop=function(shop){
var shop_list_data = shop;
console.log(shop_list_data);
$rootScope.$broadcast('to_checkout', shop_list_data);
};
The controller of the second page (a subset under the main controller)
$scope.$on('to_checkout', function(event,data) {
console.log(data);
});
But after the test, it was found that the console.log(data) of the second page failed to print, but it was successful when clicked again. Is it a routing problem? The details are as follows:
The main page is as follows. The shopping cart is hidden on the side. Click the shopping cart in the navigation bar and the shopping cart will appear on the right
Just started:
After clicking the button, the array is passed and jumps to another page, but the array is not printed:
Click the "Checkout" button again and it will print:
What is the reason for this? How to solve it?
世界只因有你2017-05-15 17:16:25
Remove ui-sref="app.checkOut", execute $broadcast first in the method, and then route the jump.
<a ng-click="checkoutShop(shopList)"><b>结算</b></a>
$rootScope.checkoutShop=function(shop){
var shop_list_data = shop;
console.log(shop_list_data);
$rootScope.$broadcast('to_checkout', shop_list_data);
$state.go('app.checkOut');
};
大家讲道理2017-05-15 17:16:25
Why add click event under rootScope? Just add it directly to the scope of the page and take a look.
phpcn_u15822017-05-15 17:16:25
$state.go can pass parameters directly when jumping to the page, why use $broadcast
Master Controller - Parent
`$rootScope.checkoutShop=function(shop){
var shop_list_data = shop;
console.log(shop_list_data);
$state.go(app.checkOut,{data:shop_list_data});
};`
Subset under main controller
.controller('XXXX', ['$rootScope', '$scope', '$stateParams',
function($rootScope, $scope, $stateParams) {
console.log($stateParams.data);
}])