Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Directives: scope vs bindToController

Since Angular v1.4, it's possible to do this:

scope: {},
bindToController: {
    name: "="
}

instead of old way of doing:

scope: {
    name: "="
},
bindToController: true

Except being more intuitive, is there any difference between them?

like image 839
Ahmet Cetin Avatar asked Jan 24 '16 15:01

Ahmet Cetin


People also ask

What is BindToController Angularjs directive?

Angular introduces a new property to the directive definition object called bindToController. BindToController enables the inherited properties to be bound to the Controller without $scope object.

How is scope in directive different from scope in controller?

By default, directives do not create their own scope; instead they use the scope of their parent, generally a controller (within the scope of which the directive is defined). We can change the default scope of the directive using the scope field of the DDO (Data Definition Object).

What is difference between controller and directive Angularjs?

A controller is usually used to contain and maintain the logic for your view, which gets bound to your view via $scope. A directive is something that you might use repeatedly and is called in your view directly through the directive name which you can pass in as an attribute.


1 Answers

Think about bindToController as a migration path for future version of Angular.

We prefer to write directives (or components) with isolated scope and bind to controller the properties you want to pass.

Binding variables from scope will gradually disappear.

In the new release of angular (1.5) you don't need to use scope or bindToController, because the scope is isolated for default and for bind variables to controller you can use bindings.

This is also useful for preventing $scope use. Read this article if you want more info about that: https://toddmotto.com/no-scope-soup-bind-to-controller-angularjs/

like image 158
eliagentili Avatar answered Oct 03 '22 17:10

eliagentili