使用$ compile以编程方式添加指令并从范围传递数据

时间:2015-09-25 07:47:38

标签: javascript angularjs angularjs-directive

我创建了一个名为ng-chart的指令:

(function () {
'use strict';
angular
    .module('app')
    .directive('ngChart', ['$http', '$compile', 'DashboardService', '$q', '$timeout', '$modal', 'FlashService', function ($http, $compile, DashboardService, $q, $timeout, $modal, FlashService) {

        return {
            restrict: 'E',
            scope:
            {
                chartObj: "=?"
            },
            template: "<div style='position:relative;'>" +
                "<span style='position:absolute;top:0px;right: 27px;' id='spanMaxRestore' title='Maximize' ng-click='btnResizeClick()'><img style='width:18px;' src='../Dashboard/Images/bakupRestore.png' alt='Restore'/></span>" +
                "<span style='position:absolute;top:0px;right: 50px;' title='Configure' ng-click='btnSettingClick()'><img style='width:18px;' src='../Dashboard/Images/setting.png' alt='Configure'/></span>" +
                "<span style='position:absolute;top:0px;right:0px;' title='Close' onclick='this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode); return false;'><img src='/precisioncare/Dashboard/Images/dialog_close.png' alt='close chart'/></span><br/>" +
                "<div style='position:absolute; width:400px;'><img src='data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQJCgAAACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkECQoAAAAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkECQoAAAAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkECQoAAAAsAAAAABAAEAAAAzIIunInK0rnZBTwGPNMgQwmdsNgXGJUlIWEuR5oWUIpz8pAEAMe6TwfwyYsGo/IpFKSAAAh+QQJCgAAACwAAAAAEAAQAAADMwi6IMKQORfjdOe82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQJCgAAACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAkKAAAALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA=='/></div>" +
                "</div>",

            link: function (scope, iElement, iAttrs, ctrl)
            {
                scope.iElement = iElement;
                $(iElement).on('resize', function () {
                    scope.resize(iElement);
                });

                $(iElement).resizable();
                $(iElement).draggable();

                alert(scope.chartObj.dashUserElementId);

                scope.$watch('chartObj', function (chartData) {

                    if (chartData != "" && chartData != undefined) {
                        $timeout(function () {

                            var elem_id = scope.chartObj.dashUserElementId; //Element id.
                            var elem_data_source = scope.chartObj.dashUserElementDataSource; //Data query to retrive the data from database.
                            var displaytypeid = scope.chartObj.dashUserElementConfigDisplayTypeId; // Display type id of current element.


                            var divContainer = iElement.find('div');
                            scope.containerToDisplay = divContainer[1];
                            var dataObject = JSON.stringify({ "element_id": elem_id, "dataquery": elem_data_source, "Configurable": scope.chartObj.dashuserelement_date_range_origin });
                            //Return data series, Query parameter, and column name.
                            DashboardService.drawDashboardElement("getElementDataQuery", dataObject).then(function (response) {
                                var resultD = JSON.parse(response.d);
                                //If result is not empty then call drawChart method with passing parameter ResultD , displaytypeId and container to display.
                                if (resultD != undefined && resultD != "")
                                    scope.drawChart(resultD, displaytypeid, scope.containerToDisplay, elem_id);
                            },
                            function (error) {
                                // promise rejected, could log the error with: 
                                console.log('error', error);
                            });

                        }, 0);
                    }

                });

            },
            controller: function ($scope) {

                $scope.drawChart = function (resultD, displaytypeid, divId,elementId) {}  // some other charting code/functions here   }  }]); })();

上面的代码片段是我的指令,使用ng-repeater在我的html视图中调用

<div ng-controller="DashboardController" style="width:100%; height:100%;">
    <div id="divChart" style="width:100%;" class="clearFloat">
        <ng-chart ng-repeat="adelement in UserConfigList" chart-obj="adelement" style='display: inline-block; margin: 20px; width: 400px; height: 450px; background-color: white'>
         </ng-chart>
    </div>  </div>

现在我想要实现的是我想在运行时在图表系列点击事件(我使用Highchart.js)上为我的仪表板添加一个图表。因此,如果用户拖动或点击饼图的任何部分,我想在运行时再绘制一个ng-chart。这是我正在尝试的:

    var template = "<ng-chart chart-obj="+ $scope.chartObj +" style='display: inline-block; margin: 20px; width: 400px; height: 450px; background-color: white'></ng-chart>";

    var newElement = $compile(template)($scope);

    $("#divChart").append(newElement);

    $scope.insertHere = newElement;

但是这似乎没有用,上面的代码中有什么遗漏/错误?我想将指令当前范围内的chart-Obj传递给相同类型的新指令(ng-chart)

1 个答案:

答案 0 :(得分:1)

你犯了一个小错误,角度没有$compile你的对象变量。相反,它通过引用它来查找范围上的变量。

所以你的解决方案是:

var template = '<ng-chart chart-obj="chartObj" style="display: inline-block; margin: 20px; width: 400px; height: 450px; background-color: white"></ng-chart>';

接下来,您希望首先创建编译元素,然后将其添加到$scope

所以这样:

var element = angular.element(template);

var compiled = $compile(element);

$('#divChart').append(element);

$timeout(function() {
    compiled($scope);
});

此外,您的指令链接功能中的$scope.$watch无法正常工作,因为它是一个深层对象,如果您需要{{1},则应添加第三个参数true }}。但是因为您将$scope.$watch中的对象定义为双向绑定变量。你甚至不需要它。