bindToController: Object in directives

2020-02-15 02:05发布

问题:

Directive bindToController can be either boolean or object, the latter is shown here:

myMod.directive('myDirective', {
  controller: 'MyDirectiveController',
  bindToController: {
    name: '@'
  }
});

But the fact that it was not documented raises questions. Why bindToController: { ... } feature was made in the first place? Are there useful scenarios for it?


Despite bindToController wasn't primarily intended for that, it is interesting to see how it is utilized now in angular.component as bindings property to fill the gap between 1.5 and 2.0, while scope bindings remain unused.

回答1:

bindToController was originally just a boolean at inception, but was migrated to allow it to be an object to be more explicit about what items/values you are binding to the controller. With it being a boolean it caused some confusion where this syntax removes that confusion about what you are adding to your controller.

The idea with why this was added was to propagate the usage of the controllerAs syntax to move away from $scope especially with the move towards angular2.

The basis for why this was added was to allow the directive injections/property bindings would now be based upon the controller instance instead of of the scope parameter.



回答2:

Just stumbled across this PR, it is quite explanatory.

I'm not sure if there is practical benefit in having two different bindings in scope: { ... } and bindToController: { ... }. But it finally brings the bindings to prototypically inherited scope as well:

bindToController: {
  text: '@text',
  obj: '=obj',
  expr: '&expr'
},
scope: true