5

我有多个指令实例,我只想针对特定实例。例如在下面的代码中,如何确保 divclass="one"是唯一由 event 触发的$rootScope.$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>
4

3 回答 3

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'});
          }
        });
      },
  };    
});

然后在$broadcast中添加参数

$rootScope.$broadcast('myEvent',{class:'one'})
于 2013-04-26T07:07:07.377 回答
1

您可以为该指令定义一个新属性,该属性引用一个回调,然后在 $on 的回调中执行:

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(“指令定义对象”部分)

于 2013-04-26T07:22:36.357 回答
0

你能用id代替class吗

<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()
于 2013-04-26T10:43:23.007 回答