javascript - Angular uses broadcast and on to jump to the page and transfer data, but no data is received after the jump.
高洛峰
高洛峰 2017-05-15 17:14:25
0
3
759

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?

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(3)
世界只因有你

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');
};
大家讲道理

Why add click event under rootScope? Just add it directly to the scope of the page and take a look.

phpcn_u1582

$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);
    }])
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template