我正在尝试使用querySelectorall来获取具有某个类名称的所有元素。我有一个问题,只能从index.html页面中的元素中获得结果。如果我尝试从部分(ng-view)HTML页面获得一个nodelist,我将获得一个空的结果。
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的部分视图中找到元素。有人想出了什么问题吗?我试图不使用jQuery。
将助手码转移到自定义指令。https://docs.angularjs.org/guide/directive
什么是指令?
在高级别上,指令是DOM元素上的标记(例如属性,元素名称,注释或CSS类),它告诉AngularJS的HTML编译器($ compile)将指定的行为附加到该DOM元素,甚至将DOM元素及其子女。
这是因为ng-view
加载了Angular后加载模板,并且您添加的JS代码是在ng-view
呈现模板之前启动的JS代码,我认为您可以通过编写指令来解决此问题。对于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
});
});
}
}
}]);