简体   繁体   English

角度将数据从控制器传递到状态

[英]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) 查看(roleUsersList.html)

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

How do I get it to display "Role id is X" in the html display? 如何在html显示中显示“角色ID为X”?

Ultimately what I'm trying to do is grab some data (an array) from an API and show it in a new view. 最终,我想做的是从API抓取一些数据(数组)并在新视图中显示。 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. 需要显示的数据将必须来自控制器(据我所知Angular),因为数据将根据用户的其他输入而有所不同。

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. 我想我可以通过服务/工厂传递数据(我认为这是单例,我认为它不适合动态环境吗?),然后使用第二个控制器,或者可以将$ rootScope与第二个控制器一起使用。 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: 或在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: 如果您不希望参数出现在查询字符串中,则可以使用params选项:

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

See this documentation 请参阅此文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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