Expand Minimize

Use bindToController in directives with controllers and two-way bindings

Use bindToController in directives with controllers and two-way bindings

CheckId NG1050501
TypeName UseBindToControllerInDirectivesWithControllers
Severity CriticalWarning
Type Directive

Using the bindToController property on directives with two-way bindings allows you to simplify the code of the controller associated with the directive. All properties specified in the bindToController property are automatically available on the this object inside the controller.

Good practice

angular.module('app').directive('someDirective', function () {
  return {
    scope: {},
    bindToController: {
      name: '='
    }
    controller: function () {
      this.name = 'Pascal';
    },
    controllerAs: 'vm',
    template: '<div>{{vm.name}}</div>'
  };
});


Bad practice
angular.module('app').directive('someDirective', function () {
  return {
    scope: {
      name: '='
    },
    controller: ['$scope', function ($scope) {
      this.name = 'Pascal';

      $scope.$watch('name', function (newValue) {
        this.name = newValue;
      }.bind(this));
    }],
    controllerAs: 'vm',
    template: '<div>{{vm.name}}</div>'
  };
});

Disclaimer: The views and opinions expressed in this documentation and in SPCAF do not necessarily reflect the opinions and recommendations of Microsoft or any member of Microsoft. SPCAF and RENCORE are registered trademarks of Rencore. All other trademarks, service marks, collective marks, copyrights, registered names, and marks used or cited by this documentation are the property of their respective owners.