加载角度脚本时,变量未定义

时间:2016-06-24 21:53:38

标签: javascript jquery angularjs d3.js nvd3.js

我有一个自定义指令,在其范围内传递一个名为'vm'的对象。该对象上有一个我需要访问的属性/值对(ccirCategoryIncidentI:3)。我正在做一个基本的console.log函数来确认它已被传入:

console.log(scope.vm.ccirCategoryIncidentI)

日志是未定义的。只有在我将该日志包装在settimeout()中之后才打印该值。

我想知道在指令开始运行后续逻辑之前是否有更好的想法“加载”属性值。在我的代码中,我需要'ccirCategoryIncidentI'变量来填充饼图楔形大小。该饼图不会呈现,因为该属性最初是“未定义的”。

(function() {
'use strict';
/* jshint quotmark: false */

angular
    .module('mybApp')
    .directive('ccirSummary', ccirSummary);

ccirSummary.$inject = ['$window', 'Accessibility', 'Tools', 'ccirSummaryChartConfig'];
function ccirSummary($window, Accessibility, Tools, ccirSummaryChartConfig)
{
    var directive = {
    restrict: 'E',
    scope: {
        vm: '='
    },
    link: ccirSummaryLink,
    templateUrl: 'scripts/tiles/ccirSummary/views/ccirSummary.html'
};
return directive;

function ccirSummaryLink(scope, element /*, attrs*/)
{
     console.log(scope.vm.ccirCategoryIncidentI) 

    scope.options = ccirSummaryChartConfig.getChartConfig();  

    console.log(scope.ccirCategoryIncidentI);   
    scope.data = [
                {
                    key: 'CAT I',
                    y: 2,
                    MyAttribute1:'DLA Avn ... CAT I',
                    MyAttribute2:'DLA Energy ... CAT I'
                },
                {
                    key: 'CAT II',
                    y: 1,
                    MyAttribute1:'DLA Avn ... CAT II',
                    MyAttribute2:'DLA Energy ... CAT II'
                },
                {
                    key: 'CAT III',
                    y: 3,
                    MyAttribute1:'DLA Avn ... CAT III',
                    MyAttribute2:'DLA Energy ... CAT III'
                },
            ];          



    var lastUpdatedDateTime;
    var forceUpdate = false;
    scope.$watch('vm.ccirdata' , function (newValue)
    {
        // We need to have some logic in here to determine if the inbound data is different from the already displayed data
        if (newValue && (newValue.lastUpdatedDateTime !== lastUpdatedDateTime || forceUpdate))
        {
            updateChart ();
        }   
    });

    var tooltip = Tools.buildTooltip ({
        base: element,
        tipText: getccirHintText
    });

    // Controls
    var openControls, resolvedControls;
    var newOpenLabelId = 'iss-open-total';
    var resolvedLabelId = 'iss-resolved-total';
    var openPrefix = 'iss-con-open-';
    var visOpenPrefix = 'iss-vis-open-';
    var resolvedPrefix = 'iss-con-resolved-';
    var visResolvedPrefix = 'iss-vis-resolved-';
    var openNavId, resolvedNavId, activeFocusId, lastBlurId;

    // Set up entry point into navigation content
    d3.select ('#' + newOpenLabelId)
    .on ('keydown', function ()
    {
        tileKeyAction ('open');
    });
    d3.select ('#' + resolvedLabelId)
    .on ('keydown', function ()
    {
        tileKeyAction ('resolved');
    });

    function updateChart()
    {
        // Build Visual Elements
        var data = scope.vm.ccirdata;

        // Build Focus Controls and Navigation
        createFocusControls (data);
        assignNavigationIds ();
        if (activeFocusId)
        {
            d3.select ('#' + activeFocusId) [0][0].focus ();
        }
    }

    function getccirHintText (data)
    {
        var ccirEventHint = getccirDataForEvent (data.ccirData, data.side);

        return [
            '<div class="ccir-legend">',
            '<div class="cooltip-label"><div class="cooltip-label is-',
            data.ccirData.impact.toLowerCase(),
            '"></div>&nbsp;',
            (data.side==='left'?'OPEN ':'RESOLVED '),
            data.ccirData.impact.toUpperCase(),
            ' ccirs:<hr class="hr-' + data.ccirData.impact.toLowerCase() + '"></div>',
            '<div class="cooltip-text"></div>',
            ccirEventHint.ccirs.join(''),
            '<div class="cooltip-text"></div>', 
            '</div>'
        ].join('');
    }

    function getccirDataForEvent(selectedBar, side)
    {
        var ccirs = [];
        var selectedImpact = selectedBar.impact.toLowerCase();
        var detailData = scope.vm.ccirdata.detail;
        var is_string;

        for(var i=0; i<detailData.length;i++)
        {
            var d = detailData[i];
            if (( isLeftOrRight(d) === side ) && (d.impact.toLowerCase() === selectedImpact) )
            {
                is_string = '<div class="cooltip-text"><div class="is-tt-new is-tt-'+d.impact.toLowerCase()+'">'+(d.isNew?'NEW':'')+ 
                '</div><div class="is-tt-text"><span class="is-tt-number">'+ d.number + ':</span> '+d.title +'</div></div>';
                ccirs.push(is_string);
            }
        }

        var ccirEventHint =
        {
            'ccirs' : ccirs
        };

        return ccirEventHint;
    }

    function isLeftOrRight( ccir )
    {

        if ( (ccir.status.toLowerCase() === 'final') || (ccir.status.toLowerCase() === 'initial/final') || (ccir.status.toLowerCase() === 'updated/final') )
        {
            return 'right';
        }
        else
        {
            return 'left';
        }
    }

    // Keyboard Interface
    function createFocusControls (nodes)
    {
        // New/Open Controls
        var result = Accessibility.buildControls ({
            navigatorId: 'iss-navigation',
            focusId: 'iss-open-focus-controls',
            prefix: openPrefix,
            visPrefix: visOpenPrefix,
            setData: nodes.open.counts,
            getId: function (d) { return d.impact.toLowerCase ();},
            navCheck: function (d) { return d.count > 0;},
            other: {
                optId: function () { return 'left';}
            },
            keyListener: keyAction,
            focusListener: focusButton,
            blurListener: blurButton
        });
        openControls = result.controls;
        openNavId = result.topnav;

        // Resolved Controls
        result = Accessibility.buildControls ({
            navigatorId: 'iss-navigation',
            focusId: 'iss-resolved-focus-controls',
            prefix: resolvedPrefix,
            visPrefix: visResolvedPrefix,
            setData: nodes.resolved.counts,
            getId: function (d) { return d.impact.toLowerCase ();},
            navCheck: function (d) { return d.count > 0;},
            other: {
            optId: function () { return 'right';}
        },
            keyListener: keyAction,
            focusListener: focusButton,
            blurListener: blurButton
        });
        resolvedControls = result.controls;
        resolvedNavId = result.topnav;
    }

    // Creates a bilateral circular linked list of all control elements
    // paired with visual controls
    function assignNavigationIds ()
    {
        // Open Controls
        Accessibility.buildNav ({
            looped: true,
            base: openControls,
            skipCheck: function (d) { return d.count === 0;},
            nodeText: function (d) { return d.impact + ' ' + d.count;},
            detailText: function (d) {
                    var ccirEventHint = getccirDataForEvent(d, 'left');
                    return '<div>. new/open ' + d.impact + ' ccirs. ' + ccirEventHint.ccirs.join (',') + '</div>';
            }
        });

        // Resolved Controls
        Accessibility.buildNav ({
            looped: true,
            base: resolvedControls,
            skipCheck: function (d) { return d.count === 0;},
            nodeText: function (d) { return d.impact + ' ' + d.count;},
            detailText: function (d) {
                    var ccirEventHint = getccirDataForEvent(d, 'right');
                    return '<div>. resolved ' + d.impact + ' ccirs. ' + ccirEventHint.ccirs.join (',') + '</div>';
            }
        });
    }

    // Main key handler
    function keyAction (e, d)
    {
        var id, el, optId;

        function getSide (e)
        {
            return d3.select ('#' + e.target.id).attr ('optid').toLowerCase ();
        }

        // Check for type of key pressed
        if (!e)
        {
            return;
        }

        switch (e.keyCode)
        {
            case Accessibility.previous:
                // Handle left arrow key (previous)
                Accessibility.focusPrevious (e);
                break;

            case Accessibility.next:
                // Handle right arrow key (next)
                Accessibility.focusNext (e);
                break;

            case Accessibility.leavelist:
                // Arrow up to the appropriate section header label depending on which 'side' we're on
                el = d3.select ('#' + e.target.id);
                optId = el.attr ('optid');
                if (optId === 'left')
                {
                    // Focus on new/open
                    d3.select ('#' + newOpenLabelId) [0][0].focus ();
                }
                else if (optId === 'right')
                {
                    // Focus on resolved
                    d3.select ('#' + resolvedLabelId) [0][0].focus ();
                }

                // Turn off tabbing for whatever the last focused element was
                d3.select ('#' + lastBlurId).attr ('tabindex', '-1');
                break;

            default:
                if (Accessibility.isActivated (e))
                {
                    // Activate and display the popup as per mouse click
                    // Pull up the previously defined optional ID to determine which side the control belongs to
                    id = e.target.id;
                    if (tooltip.isShowing)
                    {
                        tooltip.hide ();
                        d3.select ('#' + id + '-text').attr ('class', 'aria-show');
                        d3.select ('#' + id + '-detail').attr ('class', 'aria-hide');
                    }
                    else
                    {
                        // Display Popup
                        var tileBbox = element [0].getBoundingClientRect ();
                        el = d3.select ('#' + id) [0][0];
                        el.blur ();
                        setTimeout (function () {
                            tooltip.show ({ccirData:d, side:getSide (e)}, [tileBbox.left, tileBbox.top]);
                            d3.select ('#' + id + '-text').attr ('class', 'aria-hide');
                            d3.select ('#' + id + '-detail').attr ('class', 'aria-show');
                            el.focus ();
                        }, 100);
                    }
                }
                else if (e.keyCode === Accessibility.keyCode.tab)
                {
                    if (e.shiftKey && getSide (e) === 'right')
                    {
                        d3.select ('#' + resolvedLabelId) [0][0].focus ();
                    }
                    else if (!e.shiftKey && getSide (e) === 'left')
                    {
                        d3.select ('#' + newOpenLabelId) [0][0].focus ();
                    }
                }
            }

       }
    }
 }
})();

编辑:这是开发工具中对象的屏幕截图。右边的对象是'vm'对象。

enter image description here

1 个答案:

答案 0 :(得分:0)

尝试将链接函数包装在$timeout()中(函数声明可以保留在$timeout()之外):

function ccirSummaryLink(scope, element /*, attrs*/) {
    $timeout(function() {
        console.log(scope.vm.ccirCategoryIncidentI) 
        scope.options = ccirSummaryChartConfig.getChartConfig();  
        console.log(scope.ccirCategoryIncidentI);   
        scope.data = [
            {
                key: 'CAT I',
                y: 2,
                MyAttribute1:'DLA Avn ... CAT I',
                MyAttribute2:'DLA Energy ... CAT I'
            },
            {
                key: 'CAT II',
                y: 1,
                MyAttribute1:'DLA Avn ... CAT II',
                MyAttribute2:'DLA Energy ... CAT II'
            },
            {
                key: 'CAT III',
                y: 3,
                MyAttribute1:'DLA Avn ... CAT III',
                MyAttribute2:'DLA Energy ... CAT III'
            },
        ];          

        var lastUpdatedDateTime;
        var forceUpdate = false;
        scope.$watch('vm.ccirdata' , function (newValue)
        {
            // We need to have some logic in here to determine if the inbound data is different from the already displayed data
            if (newValue && (newValue.lastUpdatedDateTime !== lastUpdatedDateTime || forceUpdate)) {
                updateChart ();
            }   
        });

        var tooltip = Tools.buildTooltip ({
            base: element,
            tipText: getccirHintText
        });

        // Controls
        var openControls, resolvedControls;
        var newOpenLabelId = 'iss-open-total';
        var resolvedLabelId = 'iss-resolved-total';
        var openPrefix = 'iss-con-open-';
        var visOpenPrefix = 'iss-vis-open-';
        var resolvedPrefix = 'iss-con-resolved-';
        var visResolvedPrefix = 'iss-vis-resolved-';
        var openNavId, resolvedNavId, activeFocusId, lastBlurId;

        // Set up entry point into navigation content
        d3.select('#' + newOpenLabelId)
            .on ('keydown', function ()
            {
                tileKeyAction ('open');
            });
        d3.select ('#' + resolvedLabelId)
            .on ('keydown', function ()
            {
                tileKeyAction ('resolved');
            });
    });