2017-03-08 54 views
0

在主范围上,我有一个ng-repeat运行。如何从指令AngularJs访问控制器函数?

<table class="datatable" prevent-right-click visible="isVisible"> 
       <tr ng-repeat="t in templateData"> 
        <td confusedFunction="clickedonname(t)">{{t.templateName}}</td> 
        <td>{{t.templatePath}}</td> 
       </tr> 
      </table> 

的预防,右击是中有一个评论框,这需要第一个TD元素各自右击元素评论定制的ContextMenu。无论如何,我可以编写一个函数来获取重复元素,并传入指令,以便将注释记录到相应的元素上?另外,防止右键点击具有隔离范围。

这就是我的指令代码。

app.directive('preventRightClick', function() { 
    return { 
     restrict: 'A', 
     scope: { 
      visible: '=' 
     }, 
     link: function($scope, $ele) { 
      $ele.on('contextmenu', '*', function(e) { 
       e.preventDefault(); 
       $scope.$apply(function() { 
        $scope.visible = true; 
        $('.parented').css({right:50, top:50}).show(); 
       }) 
       e.stopPropagation(); 
      }); 

      $(document).on('click', '*', function (e) { 
       if ($(e.target).parents('.parented').length > 0) { 
       } 
       else{ 
        $('.parented').hide() 
        $ele.off('contextmenu', '*', function(){ 
         console.log('Context menu off') 
        }) 
       } 
      }) 
      $scope.confusedFunction = function(t){ 
       console.log(t.templateName) 
       console.log('coming from clickedonname') 
      } 
     } 
    }; 
}) 
+0

你想要的​​接收点击发送信息防止RightClick指令的权利? –

+0

是的,但它应该通过(t)作为参数。我需要指令中的重复对象。 @JulienTASSIN – Aijaz

+0

如果是这样,我想第一种方法是$ $在控制器函数中将事件广播到$ rootScope中,并在指令中使用相应的$ on。 –

回答

0

下面是第二种方式一个简单的例子:

HTML:

<table class="datatable" prevent-right-click visible="isVisible" foo=current.selected ng-init="current = {}"> 
    <tr ng-repeat="t in templateData"> 
    <td ng-click="current.selected = t">{{t.templateName}}</td> 
    <td>{{t.templatePath}}</td> 
    </tr> 
</table> 

指令JS:

app.directive('preventRightClick', function() { 
    return { 
     restrict : "A", 
     scope: { 
      foo: '=foo', 
     }, 
     link : function (scope, element, attrs) { 
      scope.$watch('foo', function(n) { 
      // This code will be triggered with the new t in new value on each td click 
      }) 

    } 
    }; 
}); 
+0

嗨,谢谢。但是,我如何通过函数中的t(来自ng-repeat)值?我需要那个。 – Aijaz

+0

你好,t是从ng-repeat中选择的current.selected传递给指令。您可以在监视功能中影响它并将其用于指令。 –