简体   繁体   中英

Passing params throught pages with ui-router and angularjs

I would like to pass an object to a controllerA to another controllerB and display that object. To do it, I'm using ui-router with angularjs.

This is my controllerA which build the URL using $state.href() :

const url = $state.href('home.stateA', {
    objectA: objectA
});

window.open(url, '_blank');

Now, this my route file:

.state('home.stateA', {
    url: '/stateA',
    template: '<template-b></template-b>',
    params: {
        // object: null
        objectA: null
    }
})

And finnaly, I try to get my object in my controllerB like that:

// $scope.object = $stateParams.object;
$scope.object = $stateParams.objectA;

When I console.log $scope.object , I'm getting null which is the default value in my route file.

So what's going wrong ? I'm wondering if $window.open would not be the problem.

Thanks for helping me.

I suggest you use url parameter.

.state('home.stateA', {
    url: '/stateA?object',
    template: '<template-b></template-b>',
    params: {
       object: null
    }
})

Do when open new tab page

const url = $state.href('home.stateA', {
    objectA: JSON.stringify(objectA)
});

In controllerB

$scope.object = JSON.parse($stateParams.objectA);

Because when you are open new tab. The state param is lost

window.open(url, '_blank');

You are opening a new window and trying to pass an object.

Passing a String/Number

You can pass a string/number say id, as part of the URL, if your state URL is defined like '/stateUrl/:id' and then you can access this using $stateParams.id

Sharing an object

You can use localStorage along with JSON.stringify and JSON.parse to share the object.

Set data

localStorage.setItem('object', JSON.stringify(object));

Get data

var object = JSON.parse(localStorage.getItem('object'));

I have just found the solution ->

ControllerA

const url = $state.href('stateA');
let newTab = $window.open(url);

newTab.objectA = objectA;

ControllerB:

$scope.objectA = $window.objectA

And the state is very simple :

.state('home.stateA', {
    url: '/stateA',
    template: '<template-b></template-b>',
})

I don't know if it's the best way to implement what I needed but at least it works. it may help someone else.

Thanks guys and have a nice day !

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM