【问题标题】:querySelectorAll in AngularJS partial ng-viewAngularJS部分ng-view中的querySelectorAll
【发布时间】:2015-05-03 08:25:01
【问题描述】:

我正在尝试使用 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 的部分视图中。 有人知道可能出了什么问题吗? 我正在尝试不使用 jquery。

【问题讨论】:

    标签: javascript html angularjs selectors-api


    【解决方案1】:

    将您的 helper.js 代码移动到自定义指令。 https://docs.angularjs.org/guide/directive

    什么是指令?

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

    【讨论】:

      【解决方案2】:

      这是因为 ng-view 在加载 angular 后加载模板,并且您添加的 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
                    });
                });
            }
      
         }
      }]);
      

      【讨论】:

      • 我在玩你的代码。我在编译中获得了访问权限,但 element.on(...) 永远不会触发。此外,我试图不使用 jQuery(但它目前已加载)。我还发现了一个“修复”,而不是使用链接和计时器进行编译。
      • 是的,你应该使用 $timeout 的链接功能 @control-panel 看看我的编辑
      • 是否有 element.on(...
      • element.on 有什么问题 AngularJS 将使用内置较小版本的 JQuery 的 jQLite 来处理这个问题
      猜你喜欢
      • 2014-06-15
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 2014-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多