ui-router with ControllerAs binding

All we need is an easy explanation of the problem, so here it is.

ui-router State:

$stateProvider
    .state('dashboard', {
        url: '/dashboard',
        templateUrl: 'app/dashboard/dashboard.html',
        controller: 'DashboardController as vm'
    });

In DashboardController I have:

var vm = this;
vm.title = 'Dashboard';

And in dashboard.html template:

{{vm.title}}

Why the result is showing “{{vm.title}}” instead of bind to it’s value in controller?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

There’s a controllerAs setting when you configure the state.

$stateProvider
    .state('dashboard', {
        url: '/dashboard',
        templateUrl: 'app/dashboard/dashboard.html',
        controller: 'DashboardController',
        controllerAs: 'vm'
    });

https://github.com/angular-ui/ui-router/wiki

Method 2

In your controller function, you will have to return this; at the end of the function.

var vm = this;
vm.title = 'Dashboard';
// 
return vm;

If we work with $scope instead of vm = this;:

$scope.title = 'Dashboard';
// 
return $scope;

Good Luck.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply