【问题标题】:Find deeply nested (descendants) element (id) in angular以角度查找深度嵌套(后代)元素(id)
【发布时间】:2015-12-20 17:04:52
【问题描述】:

我整天都在处理这个问题:在我的 AngularJS 指令中,我找不到具有特定 id 的嵌套元素。 jQuery 已加载并使用。

HTML:

<div class="container_header-login">
    <div class="shit" data-ng-if="!login">
        <input type="text" placeholder="username/email"/>
        <input type="text" placeholder="password"/>
        <br/>
        <button type="button" class="btn btn-primary">Login</button>
        <a href="#">Register</a>            
        <a href="#">Forgot password</a> 
        <p id="test">shit</p>
    </div>

    <div data-ng-if="login">

    </div>
</div>

指令:

var mHeaderLogin = angular.module('app.directives.mHeaderLogin', ['mMain'])// mMain-dependent due to factory call
.directive('dHeaderLogin', fHeaderLogin);
function fHeaderLogin() {
    console.log("login");
    return {
        restrict: 'AE',
        //replace: true,
        scope: {}, //isolate scope
        templateUrl: 'app/directives/header-Login/header-Login.html',
        controller: function ($scope, simpleFactory) {
            $scope.users = simpleFactory.getUsers();
            $scope.bLogin = false;
        },
        link: function (scope, element, attrs) {
            element.find("#test").bind('click', function () {
                alert("clicked");
            });
        }
    }
}

唯一有效的是使用(星号):

    link: function (scope, element, attrs) {
        element.find("*").bind('click', function () {
            alert("clicked");
        });
    }
}

【问题讨论】:

  • 你为什么用jquery而不是ng-click
  • 直接获取元素的id为$("#test').bind('click',function(){ });
  • Jax:答案基本上是“我不知道”。我是 Angular 的新手。我还不确定 ng-click 何时合适以及何时观看元素。无论如何,我仍然需要更好地理解 angular.element 以及如何使用它。阿尼尔:没用。

标签: jquery angularjs angularjs-directive find element


【解决方案1】:

data-ng-if 的两个元素都没有在调用链接函数时呈现。

您需要通过添加对$timeout() 的调用来让 Angular 完成消化:

$timeout(function () {
  element.find("#test").bind('click', function() {
    alert("clicked");
  });
});

另一个您已经讨论过但其他读者可能会错过的问题是您需要在 Angular 之前加载 jQuery。否则 Angular 将使用 jqLit​​e,对于 find()this 意味着(参见 here):

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

这是小提琴:https://jsfiddle.net/masa671/f3k55zms/

【讨论】:

  • 有效!谢谢!我将不得不调查 $timeout - 太好了!也许还应该提到 $timeout 需要作为参数添加到指令函数(fHeaderLogin)中,就像在小提琴中所做的那样
猜你喜欢
  • 1970-01-01
  • 2020-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-25
  • 2011-02-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多