Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular bindToController not working, can bind object from one controller scope to another

Tags:

angularjs

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;
        }
    };
});
like image 300
serah Avatar asked Feb 15 '17 17:02

serah


2 Answers

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.

like image 142
westor Avatar answered Sep 22 '22 05:09

westor


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
      };
    }
  }
});
like image 24
Rajath M S Avatar answered Sep 20 '22 05:09

Rajath M S