javascript - AngularJS:将函数传递给指令

标签 javascript angularjs

我在将函数传递给指令时遇到了问题(这篇文章很熟悉:AngularJS - pass function to directive,但我无法让它工作)

这是我的代码:

指令:

.directive('testdirective', function(){
  return{
    restrict: 'E',
    scope: {
      onClick: '&'
    },
    controller: 'TestController',
    controllerAs: 'tc',
    bindToController: true,
    template: '<div><button ng-click="onClick()">What UP</button></div>',
    replace: true
  }
})

Controller :

  TestController.$inject = ["$scope"];
  function TestController($scope) {
    $scope.testFunction = function(){
      alert("I´m the alert of the TestContoller");
    };
    $scope.test = 'test';
  }

HTML:

<div>
  <testdirective on-click="testFunction()"></testdirective>
</div>

我想要的听起来很简单,我只想将函数传递给指令并通过 ng-click 按钮执行它。

对我来说,我的代码看起来完全一样 like this fiddle 但我的不工作:/

如果有人给我一些提示,那就太好了。

编辑

My directive will need his own controller !

Later the function to be passed in will come from another controller !!!

最佳答案

fiddle 与您的代码不一样。

您已将指令的 Controller 设置为“TestController”。我假设您想做的是:

.directive('testdirective', function(){
    return{
        restrict: 'E',
        scope: {
            onClick: '&'
        },
        template: '<div><button ng-click="onClick()">What UP</button></div>',
        replace: true
    }
});

并在您的 HTML 中,

<div ng-controller="TestController">
  <testdirective on-click="testFunction()"></testdirective>
</div>

编辑:基于OP的评论

app.directive('testdirective', function(){
        return{
            restrict: 'E',
            scope: {
                onClick: '&'
            },
            template: '<div><button ng-click="tc.onClick()">What UP</button></div>',
            replace: true,
            controller: 'TestController',
            controllerAs: 'tc',
            bindToController: true
        }
    });

    app.controller('TestController', function ($scope) {
        console.log($scope);
    }) ;

    app.controller('AnotherController', function ($scope) {
        $scope.testFunction = function(){
            alert("I´m the alert of the TestContoller");
        };

        $scope.test = 'test';
    });

还有,你的 HTML

<div ng-controller="AnotherController">
    <testdirective on-click="testFunction()"></testdirective>
</div>

您正在将指令告诉bindToController。因此,在指令的模板中,onClick 绑定(bind)到 Controller 而不是范围。因此,您可以通过 Controller 作为指令模板中的 tc.onClick() 访问 onclick。

关于javascript - AngularJS:将函数传递给指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34991060/

相关文章:

javascript - Window.open 仅在第一次有效,否则为空白页

javascript - donut 中的馅饼上的共享工具提示?

javascript - Web服务调用期间Angularjs中的异常

javascript - $anchorScroll 仅在 ng-view 加载之后,而不是之前

javascript - AngularJS - 来自 JSON 字符串的数据绑定(bind)

javascript - 自动调整动态创建的文本区域的高度

javascript - 我如何将此内容输出到文本区域?

javascript - 如何在 React 中为列表元素定义 css 类?

javascript - 注入(inject)非 Angular JS 库

javascript - AngularJS:如何将 window.setTimeout 插入范围函数?