Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ui-router with ControllerAs binding

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?

like image 482
Oswaldo Avatar asked Apr 01 '15 13:04

Oswaldo


People also ask

What is ui in router?

UI-Router is the defacto standard for routing in AngularJS. Influenced by the core angular router $route and the Ember Router, UI-Router has become the standard choice for routing non-trivial apps in AngularJS (1. x).

What does ui sref do?

A ui-sref is a directive, and behaves similar to an html href . Instead of referencing a url like an href , it references a state. The ui-sref directive automatically builds a href attribute for you ( <a href=...> </a> ) based on your state's url.

What is ui-router in angular?

Angular-UI-Router is an AngularJS module used to create routes for AngularJS applications. Routes are an important part of Single-Page-Applications (SPAs) as well as regular applications and Angular-UI-Router provides easy creation and usage of routes in AngularJS.

What is stateProvider in AngularJS?

$stateProvider is used to define different states of one route. You can give the state a name, different controller, different view without having to use a direct href to a route. There are different methods that use the concept of $stateprovider in AngularJS.


2 Answers

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

like image 162
Brad Barber Avatar answered Oct 15 '22 14:10

Brad Barber


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.

like image 1
Aakash Avatar answered Oct 15 '22 15:10

Aakash