简体   繁体   中英

Angular Passing data to state from controller

I am trying to pass some data from a controller to a view file via routing. Not sure if I got the message across properly.

Below is my coding.

Controller

$scope.roleUsers = function(roleId){
    $scope.testvar = "Role Id Is" + roleId;
    console.log($scope.testvar);
    $state.go('roleUsers');
}

Route

.state('roleUsers', {
    url: '/roleUsersList',
    templateUrl: 'views/modals/roles/roleUsersList.html',
    controller: function($scope) {
        $scope.testvar = "Sent by route file";
    }
})

View (roleUsersList.html)

<label>asas{{ testvar }}</label>

How do I get it to display "Role id is X" in the html display?

Ultimately what I'm trying to do is grab some data (an array) from an API and show it in a new view. This is just a basic way of my initial approach to the final goal.

The data that needs to be displayed will have to come from the controller (as far as I understand Angular) since the data is going to be different depending on some other inputs from the user.

I think I can pass the data by a service/factory(this being singleton I guess it's not appropriate for a dynamic environment?) and use a second controller or may be use $rootScope with the second controller. I'm just trying to find out if this can be achieved within the same controller.

You can send parameters in your routing:

$state.go('roleUsers', { roleId: someValue });

Or in html:

<a ui-sref="roleUsers({ roleId: someValue })>..</a>

And in your definition:

.state('roleUsers', {
    url: '/roleUsersList/:roleId',
    templateUrl: 'views/modals/roles/roleUsersList.html'
})

And your controller:

function($scope, $stateParams) {
    $scope.testvar = $stateParams.roleId;
}

If you don't want the parameters to appear in your query string, you can use the params option:

.state('roleUsers', {
    url: '/roleUsersList',
    templateUrl: 'views/modals/roles/roleUsersList.html'
    params: {
        roleId: null
    }
})

See this documentation

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