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?

3
  • 2
    vm might be unkown. Try to add controllerAs : 'vm' in your route Provider for your page Commented Aug 4, 2015 at 8:33
  • 1
    you are using controllerAs in your HTML but I am not able to see any configuration for that in your router definition Commented Aug 4, 2015 at 8: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. Commented Aug 5, 2015 at 9:21

2 Answers 2

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'
})
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.