[AngularJS] New bindToController in AngularJS 1.4
bindToController is suitable for using when you have the combination of 'controller', 'controllerAs', 'templateUrl';
isolated scope is suitable for using when you have 'link function'.
The bindToController in 1.3:
angular.module('myApp', [ 'ngRoute', 'myApp.view1', 'myApp.view2', 'myApp.version' ]). config(['$routeProvider', function($routeProvider) { $routeProvider.otherwise({redirectTo: '/view1'}); }]) .directive('bind', function() { return { scope: {message: '@'}, bindToController: true, controller: 'bindController', controllerAs: 'bindCtrl', template: '<h1>{{bindCtrl.message}}</h1>' } }) .controller('bindController', function($scope) { var vm = this; });
<bind message="New bindToController in 1.4"></bind>
bindToController syntax allows your pass the message to the bindController.
template: '<h1>{{bindCtrl.message}}</h1>'
In AngularJS 1.4, bindToController can also accepts an object:
.directive('bind', function() { return { scope: true, bindToController: {message: '@'}, controller: 'bindController', controllerAs: 'bindCtrl', template: '<h1>{{bindCtrl.message}}</h1>' } })
Here we keep controllerAs and isolated scope. It works the same way.
You can also pass another object though isolate socpe:
.directive('bind', function() { return { scope: {note: '@'}, bindToController: {message: '@'}, controller: 'bindController', controllerAs: 'bindCtrl', template: '<h1>{{bindCtrl.message}} + {{note}}</h1>' } })
<bind message="New bindToController in 1.4" note="Hello"></bind>
Notice that: this time, for message we use {{bindCtrl.message}}, but note, we use {{note}}.
bindToController
When an isolate scope is used for a component (see above), and controllerAs
is used, bindToController: true
will allow a component to have its properties bound to the controller, rather than to scope. When the controller is instantiated, the initial values of the isolate scope bindings are already available.
From the Angular Doucment we can see that if we use bindToController, the isolate scope and controllerAs are required.
More: https://egghead.io/lessons/angularjs-new-in-angular-1-4-new-bindtocontroller-syntax