在AngularJS partial ng-view中的querySelectorAll

时间:2015-05-03 08:25:01

标签: javascript html angularjs selectors-api

我尝试使用queryselectorAll来获取具有特定类名的所有元素。我有一个问题,我只能从index.html页面中的元素获得结果。如果我尝试从部分(ng-view)html页面获取节点列表,我会得到一个空结果。

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 /分音/ main.html中

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

最后:helper.js(我调用的脚本就像index.html中的每个其他脚本一样)

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

所以回顾一下: 它像querySelectorAll只能在index.html中找到元素,而不能在具有ng-view的局部视图中找到。 谁知道什么可能是错的? 我试图不使用jquery。

2 个答案:

答案 0 :(得分:1)

将helper.js代码移动到custom指令。 https://docs.angularjs.org/guide/directive

什么是指令?

在较高级别,指令是DOM元素上的标记(例如属性,元素名称,注释或CSS类),它告诉AngularJS的HTML编译器($ compile)将指定的行为附加到该DOM元素甚至转换DOM元素及其子元素。

答案 1 :(得分:1)

这是因为ng-view在加载角度后加载模板,并且你添加的JS代码在ng-view呈现模板之前触发,我想你可以通过编写指令来解决这个问题对于ng-view,一旦你的ng-view内容被加载,它将激活你的jQuery代码

基本上你需要在element.on('load'事件中包装你的代码,以便确保代码在jQuery代码触发时可用

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
              });
          });
      }

   }
}]);
相关问题