Question

I'm adding classes using ng-class, but when I try to find these elements using directive, I'm not able to find them.

.factory('loadTemplate', function($compile) {
  return function(template) {
    return {
      restrict: 'E',
      replace: true,
      templateUrl: template,
      link: function(scope, el, attrs) {
        console.log(el.find('.step.disabled'));
      }
    }
  }
})

.directive('step1', function(loadTemplate) {
  return loadTemplate('processes/steps/step1.html');
})

But it doesn't find the elements (Chrome console output):

context: div
length: 0
prevObject: o.fn.init[1]
selector: ".step.disabled"
__proto__: Object[0]

processes/steps/step1.html:

<div>
  <div toggle-box>
    <div class="step" ng-class="{enabled: condition, disabled: !condition}">
...

And I'm sure that there are .disabled divs.

When I try finding the elements using only $('.step'), I can find them, because the class is already there.

How can I solve this?

Here is a Plunker: http://plnkr.co/edit/AFYMqLx0wP3tRFFWrADd?p=preview

Was it helpful?

Solution

What I needed was to wait for Angular to finish rendering the view, wrapping with a $timeout function even with a 0 timeout it will work. Like this:

Plunker example: http://plnkr.co/edit/rCqyc4AiPNLq1WtpaHJp?p=preview

.factory('loadTemplate', function($timeout) {
  return function(template) {
    return {
      restrict: 'E',
      replace: true,
      templateUrl: template,
      link: function(scope, el, attrs) {
        $timeout(function() {
          $('.step.disabled').attr('border-color', '#f00');
        }, 0);
      }
    }
  }
})

.directive('step1', function(loadTemplate) {
  return loadTemplate('processes/steps/step1.html');
})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top