Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DOM Query in Angular JS ; $(".myclass").each() Alternative [duplicate]

I am relatively new to Angular JS and I have been using jQuery for a long time. That is why I have been having a hard time shifting the jQuery inside me into angular. :D

I want to know how we can perform a DOM Query in angular. Basically, I am facing a situation where I have to do something like this

$(".myClass").each(function(){
   $(this).doSomething();
})

Can anyone suggest me how an angular programmer would do something like this.

Thanks

like image 493
aayush shrestha Avatar asked Jun 11 '14 05:06

aayush shrestha


Video Answer


2 Answers

DOM manipulations in angularjs should not be in controller, services etc... But it it should be in the only one place directives...

if you want to manipulate a DOM you should use directive and make your manipulation in there...

here is some good articles about DOM manipulations in angularjs...

Best Practice - Dom Manipulations

DOM Manipulation in AngularJS — Without jQuery

now let's try create a directive like you want. It looks like you want to manipulate element by selecting them via their class. Ok no problem so we need to create a directive which has restrict:'C' means CLASS...

here is our directive declaration... (verbose version to show everything)

app.directive('myClass',function(){
    // Runs during compile
    return {
        // name: '',
        // priority: 1,
        // terminal: true,
        // scope: {}, // {} = isolate, true = child, false/undefined = no change
        // controller: function($scope, $element, $attrs, $transclude) {},
        // require: 'ngModel', // Array = multiple requires, ? = optional, ^ = check parent elements
        restrict: 'C', // E = Element, A = Attribute, C = Class, M = Comment
        // template: '',
        // templateUrl: '',
        // replace: true,
        // transclude: true,
        // compile: function(tElement, tAttrs, function transclude(function(scope, cloneLinkingFn){ return function linking(scope, elm, attrs){}})),
        link: function($scope, iElm, iAttrs, controller) {
            console.log('Here is your element', iElm);
                    // DO SOMETHING
        }
    };
});

here is PLUNKER...

like image 200
Poyraz Yilmaz Avatar answered Oct 24 '22 08:10

Poyraz Yilmaz


Alternative for $('selector') is angular.element('selector') and alternative for $.each is angular.forEach. Thus your code would look like:

var els = angular.element('.myClass');
angular.forEach(els, function( el ){
   angular.element(el).doSomething();
})
like image 2
Kamran Ahmed Avatar answered Oct 24 '22 08:10

Kamran Ahmed