在 angular 中查找深度嵌套(后代)元素 (id)

Find deeply nested (descendants) element (id) in angular

我现在一整天都在处理这个问题:在我的 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");
        });
    }
}

在调用 link 函数时,没有呈现带有 data-ng-if 的元素。

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

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

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

find() - Limited to lookups by tag name

这是 fiddle:https://jsfiddle.net/masa671/f3k55zms/