从子ui-view组件访问父控制器

时间:2017-10-22 09:09:53

标签: angularjs angular-ui-router components

我似乎无法在这个问题上找到答案,我尝试过使用require,但没有运气它无法从组件定义中找到'settings'父级。

我希望所有'子级'路由都能访问所有'设置'方法,这样我就可以在多个状态下重用方法。

如何从嵌套的ui-view组件访问'settings'组件控制器上的方法?

的index.html

<ui-view></ui-view>

app.js

$stateProvider.register('settings', {
    abstract : true,
    component: 'settings',
    url : '/settings'
});
$stateProvider.register('settings.user', {
    component: 'settingsUser',
    url : '/:user',
});

angular.module('app', [])
    .component('settings', {
        template : `<ui-view></ui-view>`,
        controller : class Settings {
            constructor($state) {
                this.test = () => console.log('test');
                $state.go('settings.user');
            }

        }
    })
    .component('settingsUser', {
         controller : class SettingsUser {
             constructor() {
                 // want to access parent controller methods
             }
         }
    });

2 个答案:

答案 0 :(得分:1)

答案实际上非常简单,我只是没想到它可以使用路线,通过子视图,您可以通过require block简单地要求父组件。这会在子视图控制器的$ onInit生命周期阶段公开所需组件的控制器。

$stateProvider.register('settings', {
    abstract : true,
    component: 'settings',
    url : '/settings'
});
$stateProvider.register('settings.user', {
    component: 'settingsUser',
    url : '/:user',
});

angular.module('app', [])
    .component('settings', {
        template : `<ui-view></ui-view>`,
        controller : class Settings {
            constructor($state) {
                this.test = () => console.log('test');
                $state.go('settings.user');
            }

        }
    })
    .component('settingsUser', {
         require : {
             $settings : '^settings'
         },
         controller : class SettingsUser {
             constructor() {
                 // want to access parent controller methods
             }
             $onInit() {
                 this.$settings.test()
             }
         }
    });

答案 1 :(得分:0)

您可以使用$rootScope代替$scope来访问它,以获取您想要的内容。 例如,test1$rootscopetest2$scopecontroller Ctrl2我们更改了test1,它将在Ctrl1中更改见例子:

&#13;
&#13;
var app = angular.module('myApp', []);
app.controller('Ctrl1', function($scope,$rootScope) {
    $rootScope.test1 = "topController";
    $scope.test2 = "topController2";
})
.controller('Ctrl2', function($scope,$rootScope) {
    $rootScope.test1 = "mainController";
    $scope.test2 = "mainController2";
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" >
  <div ng-controller="Ctrl1">
  {{test1}} {{test2}}
  </div>
  <div ng-controller="Ctrl2">
  {{test1}} {{test2}}
  </div>
</div>
&#13;
&#13;
&#13;