如何触发指令中定义的作用域函数

How to trigger a scope function defined inside a Directive

我在我的 Angular 应用程序中使用 Dashboard 框架,它有很多指令。

在主要指令中有一些作用域函数可以使用 ng-click 从 html 模板调用,例如,当用户通过下拉菜单将小部件添加到仪表板时:

   <div class="btn-group" ng-if="options.widgetButtons">
        <button ng-repeat="widget in widgetDefs"
                ng-click="addWidgetInternal($event, widget);" type="button" class="btn btn-primary">
            {{widget.name}}
        </button>
    </div>

但是,我希望能够从我的主控制器代码中调用 addWidgetInternal()

例如,在处理放置事件时,我想通过调用 addWidgetInternal:

添加新的小部件
(function () {
'use strict';
angular.module('rage')
    .controller('MainCtrl',
        ['$scope', '$interval', '$window', 'widgetDefinitions',
        'defaultWidgets', 'gadgetInitService', initOptions]);

function initOptions($scope, $interval, $window, widgetDefinitions, defaultWidgets, gadgetInitService) {

    this.userName = 'Bob';
    this.userRole = 'Risk Analyst';

    this.descriptionText = 'Risk Engine';

    $scope.dashboardOptions = {
        widgetDefinitions: widgetDefinitions,   
        defaultWidgets: defaultWidgets,
        storage: $window.localStorage,
        storageId: 'rage.ui',
    };

    // DRAG AND DROP EVENTS         
    $scope.handleDrop = function () {

        // $scope.addWidgetInternal(); // *** CANNOT MAKE THIS CALL DIRECTLY TO OTHER DIRECTIVE !

        // **** UPDATE: a work-around to access scope function in 'dashboard' directive
        angular.element(document.getElementById('dash')).scope().addWidgetInternal();
    }

}

})();

但是在上面调用$scope.addWidgetInternal()时出现错误:

      TypeError: undefined is not a function

这里是主仪表板指令的片段 - 具体来说,link 函数:

 link: function (scope) {

          scope.widgetDefs = new WidgetDefCollection(scope.options.widgetDefinitions);

          scope.addWidgetInternal = function (event, widgetDef) {
              event.preventDefault();
              scope.addWidget(widgetDef);
          };
  }

droppable 指令如下:

.directive('droppable', function () {
  return {
    restrict: 'A',
    scope: {
        drop: '&',
    },
    require: '?dashboard',  // 'dashboard' directive is optionally requested; see 'drop' below
    link: function (scope, element, attributes, dashboardCtrl) {
        var el = element[0];

        el.addEventListener('drop', function (e) {

            if (e.preventDefault) { e.preventDefault(); }

            this.classList.remove('over');
            var item = document.getElementById(e.dataTransfer.getData('Text'));                
            this.appendChild(item.cloneNode(true));

            // call the drop function passed in from the dashboard.html 'drop' attribute
            scope.$apply(function (scope) {
                var fn = scope.drop();
                if ('undefined' !== typeof fn) {                        
                    fn(e);   // PASS THE EVENT TO CALLING FUNCTION
                }                    
            });

            return false;
        }, false);
    }
}
});

这里是 dashboard.html 视图,我在其中放置了可放置指令和仪表板指令:

    <div class="col-lg-12" data-droppable drop="handleDrop">
        <div id="dash" dashboard="dashboardOptions" class="dashboard-container"></div>
    </div>

我正在使用的可拖动指令被放置在 <img> 中,如下所示(因此,上面控制器代码中提到的拖放事件):

   <tr>
        <td >
            <img data-draggable id="chart_gridhier" src="images/chart_gridhier.jpg" title="TreeGrid" alt="Hierarchy Grid" width="80" height="95">
        </td>   
        <td><img data-draggable "id="chart_area" src="images/chart_area.jpg"  title="Area Chart" alt="Area Chart" width="80" height="95"></td>            
    </tr>

底线:我需要从控制器触发它,而不是从 html 视图模板文件触发 ng-click="addWidgetInternal($event, widget);"

**** 更新 **** 我最终将一些拖放指令逻辑移植到仪表板指令代码中。这样我就可以在与仪表板小部件定义相同的范围内处理 DROP 事件。 这是 dashboard 指令中更新的 link 代码:

link: function (scope, element) {

          // handle drop event from the gadgets drag-drop operation (see gadgets-include.html)
          var el = element[0];
          el.ondrop = function (e) {
              e.dataTransfer.dropEffect = 'move';
              var item = document.getElementById(e.dataTransfer.getData('text'));                 
              this.appendChild(item.cloneNode(true));                  
              var newWidget = _.findWhere(scope.widgetDefs, { name: item.id });
              // This will add the new widget div to the dashboard
              scope.addWidgetInternal(e, newWidget);
          };
  }

问候,

鲍勃

这通常不是实现此目的的强烈推荐方法,但我发现了一些边缘情况,在这些情况下这可能很方便——尤其是在集成 Angular 之外的代码时。

我制作了您代码的精简版 fiddle 以提供一个工作演示,您可以随意在此基础上进行构建。基本上,我通过 id 和 'digging' 将你的元素抓取到它的范围内,然后调用范围函数。在我的示例中,我将您的 chart_area 称为

angular
    .element(document.getElementById('dash')).scope().addWidgetInternal();
    .scope()
    .addWidgetInternal(message);


message 在这种情况下只是一个字符串,我从 UI 发送并在指令中注销 addWidgetInternal(),从控制器调用


JSFiddle Link