Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular ui-router: child state not accessing parent controller

I'm making use of ui.router's nested views in my Angular app. This is the relevant portion of my .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.

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:

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

What am I doing wrong?

like image 766
Tiago Avatar asked Dec 11 '25 10:12

Tiago


1 Answers

As Apédémak and dhavalcengg said, I hadn't defined controllerAs in my routes, so vm was not defined. This fixed the problem:

.state('admin', {
    url: '/admin',
    templateUrl: 'app/components/admin/admin.html',
    controller: 'AdminCtrl as vm'
})
like image 116
Tiago Avatar answered Dec 13 '25 00:12

Tiago



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!