【问题标题】:How do I access controller function from directive AngularJs?如何从指令 AngularJs 访问控制器功能?
【发布时间】:2017-03-08 19:50:58
【问题描述】:

在主范围上,我正在运行 ng-repeat。

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

prevent-right-click 是一个自定义上下文菜单,其中有一个注释框,它在第一个 td 元素上的相应右键单击元素上获取 cmets。无论如何我可以编写一个函数来获取重复的元素,并传入指令,以便可以将注释记录在相应的元素上?此外,防止右键单击具有隔离范围。

这就是我的指令代码。

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

【问题讨论】:

  • 您希望接收点击的 将信息发送到 preventRightClick 指令吗?
  • 是的,但它应该将 (t) 作为参数传递。我需要指令中的重复对象。 @JulienTASSIN
  • 如果是这样,我想第一种方法是将控制器函数中的事件 $broadcast 到 $rootScope 并在指令中使用相应的 $on。
  • 我不能使用 $rootScope 因为这将是一个非常大的企业应用程序的一部分。我刚刚写了简单的代码,以了解这样做的逻辑。
  • 第二种方法是使用你将 attrs.$observe 在指令中的属性并在控制器函数中修改它的值

标签: javascript jquery angularjs angularjs-directive


【解决方案1】:

这是第二种方式的简单示例:

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
          })

    }
  };
});

【讨论】:

  • 嘿,谢谢。但是如何在函数中传递 t(来自 ng-repeat)值?我需要那个。
  • 您好,t 是从 ng-repeat 中的 current.selected 中传递给指令的。您可以在 watch 函数中影响它并使用它的指令。
猜你喜欢
相关资源
最近更新 更多
热门标签