javascript 有没有办法从 ui.router 将变量传递给控制器​​?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19863667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 17:03:33  来源:igfitidea点击:

Is there a way to pass variables to a controller from ui.router?

javascriptangularjsangular-ui-router

提问by domokun

I have a page structured with some nested views, using ui.routerand I would like to pass some data from the parent controller to the child controller, without injecting useless services into the child controller.

In my mind, something like these would be perfect

我有一个包含一些嵌套视图的页面,使用ui.router并且我想将一些数据从父控制器传递给子控制器,而不会将无用的服务注入子控制器。

在我看来,像这样的东西将是完美的

        state('home', {
            url: "/home",
            templateUrl: "parts/home.html",
            controller: "FatherController"
        }).
        state('home.child', {
            url: "/child",
            templateUrl: "parts/home/child.html",
            controller: "ChildController",
            params: {$scope.data = $rootScope.someData}
        })


Do you happen to know if there is a way to do this?


你碰巧知道是否有办法做到这一点?

回答by Joseph Silber

If your child view is nested within the parent view, your child controller will automatically inherit the parent scope.

如果您的子视图嵌套在父视图中,您的子控制器将自动继承父范围。

You should be able to access the parent controller's data directly from the child controller.

您应该能够直接从子控制器访问父控制器的数据。

回答by vperron

Well, I guess you don't alwayshave the choice to move the data to a parent controller or such.

好吧,我猜您并不总是可以选择将数据移动到父控制器等。

My recommendation for this would be to use resolvers (https://github.com/angular-ui/ui-router/wiki#resolve) to do some magic.

我对此的建议是使用解析器(https://github.com/angular-ui/ui-router/wiki#resolve)来做一些魔术。

Here's a sample on how it could be made to work:

这是有关如何使其工作的示例:

var dataResolver = ['$scope', '$stateParams', 'Service',
    function($scope, $stateParams, Service) {
        Service.get($stateParams.objectId).then( function(obj) {
            $scope.myObject = obj;
            return obj;
        });
     };
 ];

 $stateProvider.state("foo.details", {
     "url": '/foo/:objectId', 
     "resolve": { "data": dataResolver },
     "controller": "SomeController",
     "template": "<ui-view />"
 )

And you magically get the $scope.obj data when the controller is instanciated, whatever how.

当控制器被实例化时,你会神奇地获得 $scope.obj 数据,无论如何。

回答by Prasad

You can use Query Parameters and access using $stateParams

您可以使用查询参数并使用 $stateParams 访问

https://github.com/angular-ui/ui-router/wiki/URL-Routing

https://github.com/angular-ui/ui-router/wiki/URL-Routing

回答by trungk18

Well, in my projects I use resolveof Angular UI router.

好了,在我的项目我使用resolveAngular UI router

Basically, when initializing the parent state, It will retrieve data from the server and store it into listItem. You also can separate the logic of making request to server using a serviceand inject it into config.

基本上,在初始化父状态时,它会从服务器检索数据并将其存储到listItem. 您还可以使用 a 分离向服务器发出请求的逻辑service并将其注入配置。

Suppose I click somewhere in the parent state to open the new child state with an Idas a query string. Then we get this idby $stateParamsand filter to find the correct item in listItem(using Underscore)

假设我单击父状态中的某处以打开新的子状态,并将Id用作查询字符串。然后,我们得到这个id通过$stateParams和过滤器找到正确的项目listItem(使用下划线

route.js

路由.js

.state('parent', {
    url: '/parent',
    templateUrl: 'parent-template.html',
    controller: 'ParentController',
    resolve: {
        listItem: ['$http', '$stateParams', function ($http, $stateParams) {
            return $http.get({'/GetListItem'}).then(function successCallback(response) {
                return response.data;
            }, function errorCallback(response) {
                return [];
            });
        }]
    }
})
.state('parent.child', {
    url: '/{itemId}',
    templateUrl: 'child-template.html',
    controller: 'ChildController',
    resolve: {
        item: ['$stateParams', 'listItem', function ($stateParams, bundles) {
            return _.findWhere(listItem, { Id: $stateParams.itemId });
        }]
    }
})

Then you can access to listItemand itemin the controller like below.

然后你可以像下面一样访问listItemitem进入控制器。

parent.controller.js

父控制器.js

(function () {
    function ParentController($scope, listItem) {

    }

    ParentController.$inject = ['$scope', 'listItem']

    angular.module('app').controller('parentController', ParentController)
})()

child.controller.js

子控制器.js

(function () {
    function ChildController($scope, item) {

    }

    ChildController.$inject = ['$scope', 'item']

    angular.module('app').controller('childController', ChildController)
})()