Reputation: 147
I've been sitting with this all day now: In my Directive in AngularJS I can not find a nested element with a certain id. jQuery is loaded and used.
The 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>
The Directive:
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");
});
}
}
}
The only thing that has worked is to use (the asterisk):
link: function (scope, element, attrs) {
element.find("*").bind('click', function () {
alert("clicked");
});
}
}
Upvotes: 0
Views: 746
Reputation: 2800
Neither of the elements with data-ng-if
have been rendered at the point when the link function is called.
You need to let Angular finalize the digestion by adding a call to $timeout()
:
$timeout(function () {
element.find("#test").bind('click', function() {
alert("clicked");
});
});
Another issue that you had already covered but other readers might miss is that you need to load jQuery before Angular. Otherwise Angular will use jqLite, and for find()
this means (see here):
find()
- Limited to lookups by tag name
Here's the fiddle: https://jsfiddle.net/masa671/f3k55zms/
Upvotes: 1