2013-04-26 64 views
5

我有一个指令的多个实例,我只想定位一个特定的实例。例如在下面的代码中,我如何确保class="one"的div是由事件$rootScope.$broadcast('myEvent')触发的唯一一个。AngularJS:如何针对多个实例的特定指令

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> 
+0

AFAIK它不可能,因为它是一个广播所有的儿童示波器将获得事件通知 – 2013-04-26 06:55:46

回答

4

你应该做此项检查在事件处理:

myApp.directive('myDirective', function() { 
    return { 
    restrict: 'A', 
     controller: function(scope, el, 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'}); 
      } 
     }); 
     }, 
    };  
}); 

然后在$广播添加参数

$rootScope.$broadcast('myEvent',{class:'one'}) 
+0

感谢洛杉矶吨这个真棒解决方案。 – Wishnu 2015-03-03 06:06:15

1

你可以定义该指令的新属性,它引用则是$回调内部执行的回调:

myApp.directive('myDirective', function() { 
    return { 
     restrict: 'A', 
     scope: { 
      callme: "=" 
     }, 
     controller: function(scope, el, attrs) { 
      scope.$on('myEvent', function() { 
       scope.callme(el) 
      }); 
     }, 
    };  
}); 

HTML声明:

<div my-directive class="one" callme="functionDefinedInScope"></div> 

在你的控制范围:

$scope.functionDefinedInScope = function(el) { 
    el.css({left: '+=100'}); 
} 

了解更多关于此这里: http://docs.angularjs.org/guide/directive(节“d irective定义对象“)

+0

这可能不适用于我的情况。我忘了提及我可以在不同时间针对任何一个指令。 – teggy 2013-04-26 07:39:18

0

你可以使用ID

<div my-directive id="one"></div> 
<div my-directive id="two"></div> 

,而不是在你的控制器

controller: function(scope, el, attrs) { 
    scope.moveElement = function() { 
     el.css({left: '+=100'}); 
    } 
} 

,然后代替广播,

angular.element('#one').scope().moveElement()