[英]Clicking on element not hit angularjs directive link function
It seems my li elements in angularjs directive not responding clicking event. 看来我的angularjs指令中的li元素没有响应click事件。
HTML: HTML:
<my-selbg>
<ul>
<li ng-repeat="bgimage in bgimages"><img src={{bgimage}} width="85" height="82" dir={{bgimage}}></li>
</ul>
</my-selbg>
JS: JS:
var mlwcApp = angular.module('mlwcApp', [])
.controller('BgImagesListController', function($scope, $http) {
$http.get("http://localhost:8080/webcontent/bg_images").success(function(response) {
$scope.bgimages = response;
});
})
.directive('myselbg', function(){
return {
restrict: 'E',
scope: true,
link: function(scope, element, attrs){
var elementOne = angular.element(element.children[1]);
var elementTwo = angular.element(element.children[2]);
var elementThree = angular.element(element.children[3]);
setUpBGImg = function(){
console.log('link function');
};
$(elementOne).on('click', setUpBGImg);
$(elementTwo).on('click', setUpBGImg);
$(elementThree).on('click', setUpBGImg);
}
};
});
I have 3 li elements and clicking any of them dose not hit the code in link function. 我有3个li元素,单击其中任何一个都不会在链接函数中命中代码。 Anyone has idea?
有人知道吗?
You're new to angular, by the looks of it. 从外观上,您是新手。
First off, before going any further - your directive will not even bind at all in the state it is in. You've got an element directive (which is fine, though if I were you I'd make it an attribute directive by restricting on A
, which allows you to then apply it to the list rather than an element above it) named myselbg
in your code. 首先,在进行进一步操作之前-您的指令甚至不会完全处于其所处的状态。您有一个element指令(这很好,尽管如果您愿意,我可以通过限制它使其成为属性指令在
A
,您可以将其应用到列表中,而不是应用到列表上方的元素),该代码称为myselbg
。 However, your markup is set as my-selbg
, which would then look for the angular directive mySelbg
, which does not exist. 但是,您的标记设置为
my-selbg
,然后它将寻找不存在的角度指令mySelbg
。
In addition to this, your directive will evaluate before the list is rendered (thanks to the order of priority in execution). 除此之外,您的指令将在呈现列表之前进行评估(由于执行的优先级高低)。 You have two choices to go around this:
您有两种选择可以解决此问题:
$timeout
in order to evaluate code after the current refresh cycle is done, at which point the list fully exists $timeout
来评估代码,此时列表已完全存在 ngClick
angular core directive in order to make this easy. ngClick
角形核心指令来简化此操作。 Added bonus, when your function that you evaluate starts modifying scope, you won't shoot yourself in the foot using the previous method and having to use $apply
$apply
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.