3

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?

Tiago
  • 4,233
  • 13
  • 46
  • 70
  • 2
    `vm` might be unkown. Try to add `controllerAs : 'vm'` in your route Provider for your page – Pierre-Alexandre Moller Aug 04 '15 at 08:33
  • 1
    you are using controllerAs in your HTML but I am not able to see any configuration for that in your router definition – dhavalcengg Aug 04 '15 at 08:35
  • I didn't configure controllerAs anywhere, I thought ui.router took care of that automatically when using var vm = this. That was indeed the problem. – Tiago Aug 05 '15 at 09:21

2 Answers2

2

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'
})
Tiago
  • 4,233
  • 13
  • 46
  • 70
1

I think you are talking about sharing $scope between parent and child using ui-router. here is the post that explains it with example https://stackoverflow.com/a/27699798/284225

Community
  • 1
  • 1
vijay shiyani
  • 766
  • 7
  • 19