javascript - AngularJS 部分 ng-view 中的 querySelectorAll

标签 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/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/

相关文章:

angularjs - 带数据输入的表格上的 Angular ng-repeat

javascript - Chrome 开发工具中的函数中出现意外的分号

html - ul 上的一个不方便的空白

javascript - 使用 johnpapa vm 风格的 Angular Bootstrap 模态的单元测试解析

Docker 中的 AngularJS 和 NodeJS 应用程序

html - 打印电子邮件营销的内容

javascript - 简单的字符串拆分返回对象而不是数组

Javascript:只能从输入中获取nodeValue()而不是value()?

javascript - 从 Javascript 中的对象中检索数组对象

html - 导航悬停按钮没有完全着色?