Search code examples
angularjsangularjs-directiveangularjs-scopeangularjs-1.5

AngularJS 1.5.5 Directive: $element.find() / $element.children() does not always work


This is a sample directive I have created to help understand the issue described in the title:

define(['angular'], function(angular) {
  'use strict';

  var randomElement = angular.module('RandomElement', []);

  randomElement.directive('randomElement', function() { return {
    restrict: 'E',
    transclude: false,
    template: '<div><span class="random-span"></span></div>',
    controller: function($scope, $element) {

      // This method is triggered in a ng-click binding
      $scope.findSpan = function() {
        // About 20-30% of page reloads, this returns 0 results
        console.log($element.find('.random-span'));
      }

    }
  }});

  return randomElement;
});

Note the $scope.findSpan method. That's the problem I am having: about 20-30% of page reloads, the $element.find() (or $element.children() for that matter) return 0 results.

Is there a known cause for the problem I am experiencing? Is there a solid solution for passing a reference to the sub-element defined in the template to the scope?


Solution

  • The reason was a race condition between loading jqLite and jQuery. If jQuery loaded fast enough, jQuery was used instead of jqLite and the statement worked. With only jqLite, the statement failed.

    The solution, for RequireJS, was to add jQuery as an Angular dependency in the entry file.