Angular bindToController does not work, can bind an object from one area of ​​the controller to another

I am using Angular version 1.5.7.

I have a directive that takes the name of the controller and the name of the view as strings to then call the controller accordingly.

I cannot associate the username with the calling controller with the previous controller, I see the value available in my previous controller.

Please can you advise what could be the problem?

myApp.directive("pendingRequests", function() { return { restrict: 'E', controller: "@", name: "controllerName", controllerAs: 'pendingReqCtrl', scope: {}, bindToController: { username: '=username' }, templateUrl: function(tElement, tAttrs) { return tAttrs.templateUrl; } }; }); 
+5
source share
2 answers

Thanks @westor for saving my day. I just updated my angular and started getting this problem, spent a lot of time fixing it, then found this. Therefore, I thought about some examples.

Using $ onInit in a controller function for a binding area

 controller: function () { this.$onInit = function () { // your business logic }; }; 

In my application, I was tied through an area

 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 required

 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 }; } } }); 
+8
source

Have you tried to initialize the $ onInit code?

angularjs doc says this :

Obsolescence warning: although bindings for non-ES6 class controllers are currently associated with this before the controller's constructor, this use is now deprecated. Put initialization code that relies on bindings inside the $ onInit method on the controller, instead.

I upgraded to 1.6.2, and I had to put my code in the $ onInit method to access the bindings.

+6
source

Source: https://habr.com/ru/post/1264262/


All Articles