Can a controller inherit scope from a parent controller when using ui-router

对着背影说爱祢 提交于 2019-12-09 10:55:11

问题


I have the following:

var admin = {

   name: 'admin',
    url: '/admin',
    views: {
        'nav-sub': {
            templateUrl: '/Content/app/admin/partials/nav-sub.html',
            controller: function ($scope) { $scope.message = "hello"; }
        }
    },
    controller: ['$scope', function ($scope) {
        $scope.message = "hello";
    }]
}

var subject = {
    name: 'subject',
    parent: admin,
    url: '/subject',
    views: {
        'grid@': {
            templateUrl: '/Content/app/admin/partials/grid-subject.html',
            controller: 'AdminGridSubjectController',
        }
    }
};

I would like the AdminGridSubjectController to know what the $scope.message value is but it seems not to know anything about it. Is there something I am doing wrong?

stApp.controller('AdminGridSubjectController', ['$scope', function ( $scope ) {
    var a = $scope.message;
}]);

回答1:


In order to access the scope of a parent controller in Angular UI Router use:

$scope.$parent

Then the parent scope is then freely available to you.




回答2:


Your problem might be that the name should reflect the parent in it:

var subject = {
    name: 'admin.subject',
    parent: admin,
    url: '/subject',
    ...

Here's a complete illustration of how to inherit $scope with ui-router: plunker ex




回答3:


There are several ways (and workarounds) to access parent scope data ... but controller inheritance itself, is not possible: https://github.com/angular-ui/ui-router/wiki/nested-states-&-nested-views#what-do-child-states-inherit-from-parent-states



来源:https://stackoverflow.com/questions/16634289/can-a-controller-inherit-scope-from-a-parent-controller-when-using-ui-router

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!