Prashant Bangar
Prashant Bangar

Reputation: 21

What is the difference between controller and controllerAs in AngularJS?

I am new in AngularJS, I am confused in term 'controller' and 'controller As'. Why we use both at a time? I want brief description about this both directives?

Upvotes: 2

Views: 1868

Answers (2)

Superiom
Superiom

Reputation: 113

Both things, controller and controllerAs refer to the same thing - the controller you want to work with in the specific view. They differ in the way you are going to access the properties and functions inside it. The controllerAs syntax is optional, but I highly recommend it.

Edit: controllerAs is an alias for the controller that you specify, and slightly modifies the way you approach values within the controller

If you don't specify controllerAs you will work with $scope inside the controller, and you will directly access the properties and functions from the scope of the controller, which, more or less, is a bad practice. For example:

In controller:

$scope.employer = 'John';
$scope.totalEmployees = 15;

In view:

<div>{{employer}} has {{totalEmployees}} employees</div>

Note: see how the view accesses the values directly from the scope.

However, if you specify controllerAs

controller: 'EmployeeController'

controllerAs: 'emp';

The approach is a little bit different, yet cleaner and easier to maintain:

In controller:

var emp = this;
emp.employer = 'John';
emp.totalEmployees = 15;

In view:

<div>{{emp.employer}} has {{emp.totalEmloyees} employees}}</div>

Note: Now you have to specify the alias in the view in order to access the values. This is a good practice, because as the application grows, the complexity grows as well. With controllerAs you have more control over you application and it is easier to maintain and debug.

Upvotes: 3

Inside controller directive of your html you can access the values assigned to your $scope variable, But if you use controllerAs = "vm" syntax;

You may simply (in your controller) do:

var vm = this;
vm.myModel = 'my model text'

So you don't need to assign values to $scope and in your html you can access it

<div>{{vm.myModel}}</div>

Upvotes: 1

Related Questions