2013-04-26 66 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()