I am using Angular 1.5.7 version.
I have a directive that takes in the controller name and view name as strings to then invoke the controller respectively.
I am not able to bind username to the invoking controller from the previous controller, I see the value available in my previous controller.
Please can you advise what could be the issue?
myApp.directive("pendingRequests", function() {
return {
restrict: 'E',
controller: "@",
name: "controllerName",
controllerAs: 'pendingReqCtrl',
scope: {},
bindToController: {
username: '=username'
},
templateUrl: function(tElement, tAttrs) {
return tAttrs.templateUrl;
}
};
});
Did you try $onInit to initialize your code?
angularjs doc says this:
Deprecation warning: although bindings for non-ES6 class controllers are currently bound to this before the controller constructor is called, this use is now deprecated. Please place initialization code that relies upon bindings inside a $onInit method on the controller, instead.
I updated to 1.6.2 and I had to put my code into $onInit method to access the bindings.
Thank you @westor you saved my day. I just updated my angular and started getting this issue, spent a lot of time fixing it, then I found this. So thought of giving some examples.
Using $onInit in your controller function for binding scope
controller: function () {
this.$onInit = function () {
// your business logic
};
};
In my app, I was binding through scope
myApp.directive('pendingRequests', function () {
return {
scope: {
item:'='
},
bindToController: true,
controller: controller,
controllerAs: 'vm',
controller: function ($scope) {
console.log(this.item); // doesn't logs
this.$onInit = function () {
console.log(this.item); // logs your other directives object
};
}
}
});
using require
myApp.directive('pendingRequests', function () {
return {
scope: {},
bindToController: {},
controller: controller,
controllerAs: 'pendingReqCtrl',
require: {
parent: '^otherDirective'
},
controller: function ($scope) {
console.log(this.parent); // doesn't logs
this.$onInit = function () {
console.log(this.parent); // logs your item object
};
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With