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

I am relatively new to Angular JS and I have been using jQuery for a long time. That's why it was hard for me to move jQuery inside me in angular .: D

I want to know how we can execute a DOM request in angular. Basically, I came across a situation where I need to do something like this

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

Can someone tell me how an Angular programmer would do something like this.

thanks

+7
javascript jquery angularjs
source share
2 answers

DOM manipulations in angularjs should not be in the controller, services, etc. But this should only be in one place of the directive ...

if you want to manipulate the DOM, you must use the directive and do your manipulation there ...

here are some good articles on manipulating the DOM in angularjs ...

Best Practice - Manipulating Home

DOM manipulation in AngularJS - No jQuery

Now try creating the directive as you want. It looks like you want to control an element by selecting them through your class. There is no problem, so we need to create a directive that has a restrict:'C' means CLASS ...

here is our declaration of the directive ... (detailed version to show all)

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

+4
source share

The alternative for $('selector') is angular.element('selector') , and the alternative for $.each is angular.forEach . So your code will look like this:

 var els = angular.element('.myClass'); angular.forEach(els, function( el ){ angular.element(el).doSomething(); }) 
+2
source share

All Articles