从 DOM 获取元素

get element from DOM

本文关键字:元素 获取 DOM      更新时间:2023-09-26

你好,我正在尝试从角度指令中的 DOM 获取元素。

此元素:

点击图片

我试图通过未知 id 获取此元素,这是代码:

传递用户对象:

<dashboard user="user" action="pageSelect(name,pageNumber)"></dashboard>

在模板网址指令中:

<section>
<li id="Dashboard{{$index}}" ng-repeat="dashboard in user.NavigationMenu">
    <h3 class="PovDashboard">
        <i class="fa fa-tachometer"></i>
        {{dashboardName}}
    </h3>
    <ul class="povPages">
        <li ng-repeat="page in dashboard.Pages"> <i class="povIconRight fa fa-angle-double-right"></i></li>
    </ul>
</li>

这就是问题所在:

  scope.$watch('user', function(newValue) {
            if (newValue !== undefined) {
                console.log(scope.user.NavigationMenu[0].Pages);
                var defaultDashboard = scope.user.DefaultDashboardID;
                console.log(scope.user);
                angular.forEach(scope.user.NavigationMenu,function(value,key){
                    if(value.ID === defaultDashboard){
                        console.log(key);
                        // i tried everything 
                        var s = '#Dashboard' + key;
                        var e = angular.element.find(s)
                        //e is  empty
                        console.log(e);
                        //i'm trying to do
                        //e.('.povPages').first().css("display","block"); 
                    }
                })

            }
        });

提前致谢

您没有使用 jqLite 包装器angular.element()语法正确,我想您应该尝试一下:

angular.element(s).find('ul').css('display', 'block');

如果您不使用jQuery,那么.find()将仅查找标签名称。

从文档中:

find(( - 仅限于按标记名称查找


或者最好用ng-show/ng-hide的角度方式来做:

<ul class="povPages" data-ng-show='isVisible'>

立即初始化$scope.isVisible = false; .$watch()执行此操作:

scope.$watch('user', function(newValue) {
    if (newValue != undefined) {
        console.log(scope.user.NavigationMenu[0].Pages);
        scope.isVisible = newValue != undefined ? true : false;
        console.log(scope.user, scope.isVisible);
    }
});

示例演示:

angular.module('demoapp', []).controller('demoCtrl', ['$scope', '$timeout',
  function($scope, $timeout) {
    $scope.arr = [{
      text: "one"
    }, {
      text: "two"
    }];
    $scope.isVisible = false;
    $timeout(function() {
      $scope.isVisible = true;
    }, 2000);
  }
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app='demoapp' ng-controller='demoCtrl'>
  <div ng-repeat="obj in arr">
    <h1>see if list is visible == {{isVisible}} {{obj.text}}</h1>
    <ul ng-show='isVisible'>
      <li>should be visible after value change. {{obj.text}}</li>
    </ul>
  </div>
</div>