HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Acceptable way of using jQuery methods in Angular directives

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
wayangularmethodsjqueryusingacceptabledirectives

Problem

Here is my plunker example of what I am doing.

jQuery is a great way to use slide transitions and seem to work well with angular as long as you are only using the methods on the element object inside a directive.

Basically I am using a directive for divs I want to slide toggle which listens for a broadcast from the controller which happens when the click function is called in the controller.

I am not using jQuery selectors and am only calling slideToggle() on the angular element.

Is this an acceptable angular way of doing this? If not, what is?

HTML


    
    
    
    
    

  
    
        
            
            
            Login
            
                Click here
            
        
        
            
            
            
            Sign up
            
                Click here again
            
        
        
            X
        
    
  


JavaScript

var myApp = angular.module("myApp", []);

myApp.controller('mainCtrl', function($scope, $rootScope) {
  $scope.toggleClick = function(){
    $rootScope.$broadcast("toogleDiv","");
  };
});

myApp.directive('toggle', function () {
    return {
        restrict:'C',
        link: function (scope, element, attrs) {
            scope.$on("toogleDiv", function(e, val){
              element.slideToggle();
            });
        }                  
    }
});

Solution

I see no reason not to use JQuery animations. If you want to have your app pure angular, use angular animations.

The main issue usually being nagged about is view (dom) manipulation code in the controller, so the directive is the way to go, for sure.

The event broadcast is overkill though, just put the onclick in the directive too :) unless you are planning to put the link outside of <div class="toggle"....

Context

StackExchange Code Review Q#59670, answer score: 2

Revisions (0)

No revisions yet.