我有一个指令的多个实例,我想只针对一个特定的实例.例如,在下面的代码中,我如何确保class =“one”的div是唯一一个由事件$rootScope触发的div.$broadcast(‘myEvent’).
JS:
myApp.directive('myDirective',function() { return { restrict: 'A',controller: function(scope,el,attrs) { scope.$on('myEvent',function() { el.css({left: '+=100'}); }); },}; });
HTML:
<div my-directive class="one"></div> <div my-directive class="two"></div>
解决方法
您应该在事件处理程序中执行此检查:
myApp.directive('myDirective',function() { return { restrict: 'A',attrs) { scope.$on('myEvent',function(ev,args) { //do the check - you could provide a function,a value or something else if(el.hasClass(args.class)){ el.css({left: '+=100'}); } }); },}; });
然后在$broadcast中添加参数
$rootScope.$broadcast('myEvent',{class:'one'})