当我有一个断点时,为什么我的angular1.6控制器没有正确绑定

时间:2017-09-21 03:24:31

标签: angularjs angular-directive angular1.6

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();
            }
        };
    }
]);

当我运行代码而没有一个断点时,我得到了这个 enter image description here

绑定optionsDataoptionsSelected和allSubtypesSelected`正在按预期工作。但出于某种原因当我在代码中放置一个断点(在上面的代码中指定)时,我得到以下内容

enter image description here

我没有改变任何事情!我的代码无效,因为当我调试到我的代码时,$ ctrl.optionsData未定义,但我不确定原因。

1 个答案:

答案 0 :(得分:1)

您可以使用AngularJS的$onInit(),而不是从您的控制器功能调用init。

在Angular有机会设置传入的变量/绑定之前,正在调用init()函数。在init函数中的任何断点都将在控制器完全初始化之前发生。

来自AngularJS文档:

$onInit() - 在构造了元素上的所有控制器并初始化其绑定之后(在此元素上的指令的前置和后置链接函数之前),在每个控制器上调用。这是为控制器放置初始化代码的好地方。