2

I'm using a Dashboard framework in my Angular application which has lots of directives.

Within the main directive there are some scope functions which are getting called from an html template using ng-click, for example, when a user adds a widget to the dashboard via a dropdown menu :

   <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>

However, I'd like to be able to call addWidgetInternal() from my main controller code.

For example, upon handling a drop event I'd like to add the new widget by calling 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();
    }

}

})();

But I get an error when calling $scope.addWidgetInternal() above:

      TypeError: undefined is not a function

and here's a snippet from the main dashboard directive - specifically, the link function:

 link: function (scope) {

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

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

the droppable directive is the following:

.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);
    }
}
});

and here's the dashboard.html view where I place both droppable and dashboard directives:

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

The draggable directive I'm using is placed inside an <img> as follows (hence, the drop event mentioned in the above controller code) :

   <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>

Bottom line: instead of triggering ng-click="addWidgetInternal($event, widget);" from an html view template file, I need to trigger it from a controller.

**** UPDATE **** I ended up porting some of the drag-drop directive logic INTO the dashboard directive code. This way I can handle the DROP event within the same scope as the dashboard widget definitions. Here's the updated link code in the dashboard directive :

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

regards,

Bob

scniro
  • 16,844
  • 8
  • 62
  • 106
bob.mazzo
  • 5,183
  • 23
  • 80
  • 149
  • 3
    the problem is that you are trying to fire a function in a lower scope.. usually when you are going to need to fire methods in different controllers you use a service.. – rahpuser Jan 08 '15 at 19:42
  • @rahpuser - it's true, and I appreciate the suggestion. I do have many services/factories, but the primary widget functionality exists within this directive so it might not be trivial to port that into a service. Perhaps I can mimic the ng-click behind the scenes - i.e. during the draggable directive on my page. – bob.mazzo Jan 08 '15 at 20:32
  • trying to follow some advice in this post, but it's a bit tricky - http://stackoverflow.com/questions/16881478/how-to-call-a-method-defined-in-an-angularjs-directive – bob.mazzo Jan 08 '15 at 22:04

1 Answers1

2

This generally is not a highly recommended way to accomplish this, but I have found edge cases where this can be handy- especially when integrating code that is outside of Angular.

I crafted a light version fiddle of your code to provide a working demo which you can feel free to build on from there. Basically, I am grabbing your element by id and 'digging' into it's scope, then calling the scope function. In my example, I call your chart_area like

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


message in this case is just a string I am sending from the UI and logging out in addWidgetInternal() in the directive, called from the controller


JSFiddle Link

scniro
  • 16,844
  • 8
  • 62
  • 106
  • thank you. I'm experimenting with that now. I've also posted a question regarding the use of the REQUIRE option, allowing me to call directly into the 'dashboard' directive from the 'droppable' directive - http://stackoverflow.com/questions/27863573/using-the-angularjs-require-option-to-call-into-another-directive – bob.mazzo Jan 09 '15 at 15:27
  • Did this work for you? I also attempted to answer your other question. View answer http://stackoverflow.com/a/27864420/1464112. Best of luck – scniro Jan 09 '15 at 15:59
  • sal - I never would have guessed that work-around you provided. It does indeed call straight into addWidgetInternal() of my dashboard directive. I updated the elementById to grab 'dash' instead, which is where I'm dropping on. – bob.mazzo Jan 09 '15 at 16:09
  • I only need to figure out now how to pass the original two parameters from that ng-click="addWidgetInternal($event, widget);". I need to get the event and widget type in the 'drop' listener of the droppable directive. – bob.mazzo Jan 09 '15 at 16:12
  • 1
    No problem, just pass `$event` from UI and update all function signatures until the directive. Here is a fiddle doing so with the same example. http://jsfiddle.net/aregnfy1/ Please consider accepting answers if they are working for you – scniro Jan 09 '15 at 16:14
  • I ended up creating the `e.ondrop` event in the link section of the `'dashboard'` directive. This way I can now get access to the widgetDefs object, and all its options. See updated section of my post. – bob.mazzo Jan 09 '15 at 23:29