简体   繁体   English

Angular ui-router:子状态不访问父控制器

[英]Angular ui-router: child state not accessing parent controller

I'm making use of ui.router 's nested views in my Angular app. 我在Angular应用程序中使用了ui.router的嵌套视图。 This is the relevant portion of my .config : 这是我的.config的相关部分:

$urlRouterProvider.otherwise('/');

$stateProvider
.state('home', {
    url: '/',
    templateUrl: 'app/components/home/home.html',
    controller: 'HomeController'
})
.state('admin', {
    url: '/admin',
    templateUrl: 'app/components/admin/admin-dashboard.html',
    controller: 'AdminCtrl'
})
.state('admin.page-1', {
    templateUrl: 'app/components/admin/page-1/page-1.view.html',
    controller: 'AdminCtrl'
})

What's happening is, although the admin.page-1 view is being loaded correctly inside the admin view, it seems to not have access to AdminCtrl . 发生了什么,虽然在admin视图中正确加载了admin.page-1视图,但它似乎无法访问AdminCtrl

This is the controller: 这是控制器:

(function() {
    'use strict';

    angular
        .module('peaches')
        .controller('AdminCtrl', Controller);

    Controller.$inject = ['$scope'];

    function Controller($scope) {
        var vm = this;

        vm.test = "Hello."
        console.log(vm.test);

        vm.organization  = {
            name: "Western Fund"
        };

        activate();

        function activate() {

        }
    }
})();

The console.log(vm.test) DOES work when I go to admin.page-1 , but it does not seem to load inside my nested view, page-1.view.html , here: 我转到admin.page-1console.log(vm.test)工作正常,但它似乎没有加载到我的嵌套视图中, page-1.view.html ,这里:

<div class="col-xs-12">
    <h1>{{vm.test}}</h1>
</div>

What am I doing wrong? 我究竟做错了什么?

As Apédémak and dhavalcengg said, I hadn't defined controllerAs in my routes, so vm was not defined. 正如Apédémak和dhavalcengg所说,我没有在我的路线中定义controllerAs ,所以没有定义vm This fixed the problem: 这解决了这个问题:

.state('admin', {
    url: '/admin',
    templateUrl: 'app/components/admin/admin.html',
    controller: 'AdminCtrl as vm'
})

I think you are talking about sharing $scope between parent and child using ui-router. 我想你在谈论使用ui-router在父母和孩子之间分享$ scope。 here is the post that explains it with example https://stackoverflow.com/a/27699798/284225 这是用例子https://stackoverflow.com/a/27699798/284225解释它的帖子

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

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