control-panel
control-panel

Reputation: 275

querySelectorAll in AngularJS partial ng-view

I'm trying to use queryselectorAll to get all elements with a certain class name. I have a problem where I can only get results from elements in the index.html page. If I try to get a nodelist from a partial (ng-view) html page I get an empty result back.

App.js

var myApp = angular.module('myApp', ['ngRoute', 'articleControllers']);
myApp.config(['$routeProvider', function($routeProvider){
    $routeProvider.
    when('/main', {
        templateUrl: 'lib/partials/main.html',
        controller: 'MainController'
    })
}]);

controller.js

var articleControllers = angular.module('articleControllers', []);
articleControllers.controller('MainController', ['$scope', '$http', function ($scope, $http){
    $http.get('http://...').success(function(data) {
        $scope.articles = JSON.parse(data);
    });
}]);

index.html

(body, header, ...)
    <section ng-view>
    </section>
(footer, ...)

lib/partials/main.html

...
<div class="nextArticle">
    <button class="next_btn" title="View next article"> link text</button>
</div>
...

finally: helper.js (which is a script I call like every other script in index.html)

var elList = document.querySelectorAll('.next_btn');
Array.prototype.forEach.call(elList, function(el) {
    console.log("Found: " + el);
});

So to recap: Its like querySelectorAll can only find elements in the index.html and not in the partial views with ng-view. Anyone an idea of what could be wrong? I'm trying not to use jquery.

Upvotes: 1

Views: 989

Answers (2)

Pankaj Parkar
Pankaj Parkar

Reputation: 136174

That is because ng-view load the template after angular gets loaded, and the JS code which you have added is firing before the ng-view renders the template, I think you could solve this by writing a directive for ng-view that will will fire your jQuery code once your ng-view content gets loaded

Basically you need to wrap your code in element.on('load' event so that it will ensure that code will available when jQuery code is firing

app.directive('ngView', ['$timeout', function($timeout){
   return {
      restrict: 'AE',
      link: function(element, attrs){
          $timeout(function(){
              element.on('load', function(event){
                 //your jQuery code will lie here 
                 //that will also get the DOM of ng-view template
              });
          });
      }

   }
}]);

Upvotes: 1

Jahanzaib Aslam
Jahanzaib Aslam

Reputation: 2834

Move your helper.js code to custom directive. https://docs.angularjs.org/guide/directive

What are Directives?

At a high level, directives are markers on a DOM element (such as an attribute, element name, comment or CSS class) that tell AngularJS's HTML compiler ($compile) to attach a specified behavior to that DOM element or even transform the DOM element and its children.

Upvotes: 1

Related Questions