Recently, I encountered a problem while using bindToController in my angular directives. Specifically, I was struggling to access properties of the class MultiSelect within my controller method. In this context, 'this' refers to the $scope due to the controllerAs syntax. However, I also needed to figure out how to access my searchService service.
/// <reference path="../../../../definitions/app.d.ts" />
module App.directives
{
'use strict';
class MultiSelect implements ng.IDirective
{
restrict = 'E';
templateUrl = 'directives/multi-select/multi-select.directive.html';
scope = {};
bindToController = {
value: '='
};
controllerAs = 'multiSelect';
constructor(private searchService: App.ISearchService) {
}
controller()
{
console.log(this)
// prints {value: undefined}
// which matches bindToController
this.searchService.get();
// TypeError: Cannot read property 'get' of undefined
}
link = ($scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) => {
}
static factory(): ng.IDirectiveFactory
{
const directive = (searchService: App.ISearchService) => new MultiSelect(searchService);
return directive;
}
}
angular.module('App').directive('multiSelect', ['searchService', MultiSelect.factory()]);
}