我有一个只触发一次的指令,只有当你在带有指令的页面上启动时才会触发。
我做错了什么?
HTML -
<div class="body">
<a href="#/systems"><div class="viewBySys"></div></a>
<div ng-view class="container reveal-animation"></div>
<a href="#/applications"><div class="viewByAppl"></div></a>
</div>
<script type="text/ng-template" id="appls.html">
<div sample class="appls myElement" ng-repeat="app in appData">
<a href=#/applications/{{app.uri}}>
<div>
<img ng-src="{{app.imageS}}"/>
{{app.name}}
</div>
</a>
</div>
</script>
JS -
app.directive('sample', function () {
return {
restrict: 'A',
transclude: false,
link: function (scope, element, attributes) {
element.on('click', function () {
$(element).trigger("myEvent.sample");
});
},
};
});
$(document).ready(function () {
$('img').on('dragstart', function (event) { event.preventDefault(); });
$(".myElement").on("myEvent.sample", function (e) {
alert('clicked!');
console.log("made it");
});
});
我想我正确使用指令,但我对Angular很新,我确定我在Jquery中错误地使用它。
答案 0 :(得分:3)
尝试将以下内容添加到document.ready(..)
功能中。
console.log('sample count: '+$(".myElement").length);
我认为您会发现它会将sample count: 1
打印到控制台。
在您的模板中
<div sample class="appls myElement" ng-repeat="app in appData">
ng-repeat
指令会创建其他DOM元素,但这会在Angular摘要周期中发生。在文件就绪后执行正在发生的事情。
如果要从AngularJS广播自定义jQuery事件。选择一个你知道存在的DOM元素。
在您的指令中更改为
$('body').trigger('myEvent.sample', $(element));
现在,您可以在JavaScript的其他位置捕获该事件。
$('body').on('myEvent.sample',function(event, element){
console.log("made it");
console.log(element); // the argument for the event.
});