ui-router with ControllerAs binding

2019-04-19 15:27发布

问题:

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?

回答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



回答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.