我正在尝试使用 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/partials/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 的局部 View 中找到元素。 任何人都知道什么可能是错的? 我尽量不使用 jquery。
最佳答案
将您的 helper.js 代码移至自定义指令。 https://docs.angularjs.org/guide/directive
什么是指令?
在高层次上,指令是 DOM 元素上的标记(例如属性、元素名称、注释或 CSS 类),它告诉 AngularJS 的 HTML 编译器($compile)将指定的行为附加到该 DOM 元素,甚至转换DOM 元素及其子元素。
关于javascript - AngularJS 部分 ng-view 中的 querySelectorAll,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30011710/