Update: It must have been something stupid in another part of the code. It works now, so the bindToController syntax is fine.
We are using AngularJS 1.4, which introduced a new way to use bindToController in directives.
After quite a bit of reading (and maybe not understanding everything), we defined our directive like this:
.directive('mdAddress', function mdAddress() {
var directive = {
restrict: 'EA',
scope: {},
bindToController: {
address: '='
},
templateUrl: 'modules/address/address.html',
controller: AddressController,
controllerAs: 'dir'
};
Calling it from another view like this:
<md-address address="vm.address"></md-address>
Having previously defined in the view controller:
vm.address = {
street: null,
countryCode: null,
cityCode: null,
postalCode: null
};
Referencing the variables in the directive template like this:
<md-input-container>
<label>{{'ADDRESSNUMBER' | translate}}</label>
<input type="number" ng-model="dir.address.streetNumber">
</md-input-container>
We spent 4h trying to figure out why our directive was not working. Well, it was working, but the two-way binding between the controller and the directive was not, vm.address.street
was hopelessly set to null.
After a while, we just tried the old way:
.directive('mdAddress', function mdAddress() {
var directive = {
restrict: 'EA',
scope: {
address: '='
},
bindToController: true,
templateUrl: 'modules/address/address.html',
controller: AddressController,
controllerAs: 'dir'
};
And it magically worked. Any idea WHY?
modules/address/address.html
template? If you were trying to referencevm
at all in the template, then that would cause a null issue sincevm
doesn't exist in the scope of your directive. Also if you were trying to just bind toaddress
in the directive template, that also wouldn't exist as you're binding your controller asdir
, so it would have to bedir.address
dir
:<input type="number" ng-model="dir.address.streetNumber">
. I edited the main post to clarify this. Thanks.