2
HB.Core.Directives.directive('hbMultiselect', [
    function() {
        return {
            restrict: 'E',
            templateUrl: '/hb-core/library/directives/hb-multiselect/hb-multiselect-ptl.html',
            scope: {},
            controllerAs: '$ctrl',
            bindToController: {
                optionsData: '<',
                optionsSelected: '=',
                allSubtypesSelected: '='
            },
            controller: function() {
                var $ctrl = this;

                // $ctrl.$onInit = function() {
                //     console.log(this); // Tried this... didn't work either
                // };

                function init() {
                    $ctrl.isExpanded = false;
                    $ctrl.optionsDisplay = [];
                    $ctrl.tags = [];
                    console.log("------")
                    console.log($ctrl);
                    console.log("------")     
>>>>>>>>>>>>>>>>>>>>**BREAK POINT HERE**                   
                }
                init();
            }
        };
    }
]);

When I run the code without a break point I get this enter image description here

the bindings optionsData, optionsSelected and allSubtypesSelected` are working as expected. But for some reason when I put a breakpoint in the code (specified in the code above) I get the following

enter image description here

I haven't changed anything! My code isn't working because when I debug into my code $ctrl.optionsData is undefined but I'm not sure why.

Luke Xu
  • 2,302
  • 3
  • 19
  • 43

1 Answers1

1

You can use AngularJS's $onInit() instead of calling init from your controller function.

The init() function is being called before Angular has a chance to set the variables / bindings passed in. Any break-point in your init function will happen before the controller has fully initialised.

From the AngularJS documentation:

$onInit() - Called on each controller after all the controllers on an element have been constructed and had their bindings initialized (and before the pre & post linking functions for the directives on this element). This is a good place to put initialization code for your controller.

BrendanBenting
  • 571
  • 6
  • 8
  • 1
    Ugh.. I actually tried that as you can see in my comments at the very top but for some reason it didn't work. I tried it again and it worked :/ Thanks for the explanation though! – Luke Xu Sep 21 '17 at 03:35
  • Did you mean Controller instead of Component (Angular 2+)? `$onInit` works correctly for controllers (here the controller is defined inside of the provided code's directive definition). – BrendanBenting Sep 21 '17 at 09:23
  • @RamsingNadeem I thought $onInit worked on controllers only too. My code is working after I switched it to $onInit though :/ – Luke Xu Sep 21 '17 at 14:42