0

I am accessing dom elements in my controller function. Since my controller run before my entire dom has rendered, elements like $(".memos .inner") does not register. So I am using $(window).load which works great.

My question: What's the most appropriate way to run a function in angular that uses dom elements? I know it's looked down upon to use jQuery in Angular. So whats the angular way to do this? $(".memos .inner") is an element already defined in my view.

app.controller('useSpreadsheetData', function(){

  $(window).load(function() {
    var slideIndex = 0;
    var slideCount = $(".memos .inner").children().length;
    var slideWidth = 100/slideCount;

    $(".memos .inner").css({width:slideCount * 100 + '%'});
    var holderWidth = slideCount*100;
    var increment = holderWidth/slideCount;

    //set the left position for each slide
    $(".memos .inner").find(".section").each(function(slide) {
      var left_pos = (slideWidth * slide) + '%';
      $(this).css({"left":left_pos});
      $(this).css({"width": slideWidth + '%'});
    });
  });

});
Neha Sohail
  • 239
  • 3
  • 19
  • It's obvious that you're on Chapter 1 Page 1 of the "How To Angular" book. Read about `ngClass`, `ngStyle` and on some other basic features in angular – Alon Eitan Feb 10 '17 at 19:11
  • It depends on what version you're on. You want to use [angular.element](https://docs.angularjs.org/api/ng/function/angular.element) - v1 or [ElementRef](https://angular.io/docs/ts/latest/api/core/index/ElementRef-class.html) - v2. You should note in v1 `angular.element` is an alias to the jQuery lite wrapper, so the DOM element is accessible with `angular.element('selector')[0]`. – tao Feb 10 '17 at 19:24
  • @AndreiGheorghiu thanks. `angular.element('.memos .inner')[0])` seems to only work if I use window as well. Is there an alternate more angular appropriate solution to do this? Using ngStyle or ngClass? – Neha Sohail Feb 10 '17 at 19:53
  • No, those are just bindings to `$scope` properties getting evaluated in order to output `style` properties or classes. I'll explain in an answer. Can't fit it in a comment :) – tao Feb 10 '17 at 19:57
  • @AndreiGheorghiu thanks. I'm looking for an answer that doesn't require timeout or window.load to change dom elements in angular. – Neha Sohail Feb 10 '17 at 20:00
  • [`$timeout`](https://docs.angularjs.org/api/ng/service/$timeout) without a duration defaults to `0` duration using `.digest()` cycle and fires after DOM has been parsed. I don't know any other way to make sure elements are ready to be selected. Unlike `$(window)` `ready` or `load` events, it makes sure angular has been loaded and parsed. – tao Feb 10 '17 at 20:03
  • I found [this great answer](http://stackoverflow.com/a/29571230/1891677). It's a directive you can place on that particular element. It will call your scope function when it has been loaded. Have a look around at the other answers, too. – tao Feb 10 '17 at 20:16

0 Answers0