Angularjs 指令从父控制器调用函数

Angularjs directives call function from Parent's controller

因为我的问题只是代码中少了一个字,所以我会写出解决方法。

我认为它可能对其他学习者有帮助。

文件列表:

您的 app.js 正在使用路由提供程序来显示您的视图。在此示例中,您只有一个视图,即 page.html。此页面由 mycontroller.js.

控制

您希望 page.html 显示几个指令,每个指令在设计上都非常不同,因此您已将模板放入 mydirectives.html。

管理您的指令的文件是 mydirectives.js。

我们的示例是从 mydirective.html 调用在 mycontroller.js 中声明的函数。该功能只会发送警报。

app.controller('mycontroller', function ($scope) {
    $scope.sendAlert = function () {
        alert("It works !");    
    }
 });

现在您正在定义指令mydirective.html。我们将只为示例添加一个简单的按钮。

... your design

<button ng-click="callFunction()" type="button">Call the function</button>

... end of your design

现在您已经设置了指令,您需要使用可以包含多个指令的文件 mydirectives.js 来管理它。

app.directive('test', function() {
    return {
        restrict: 'E',
        templateUrl: 'mydirectives.html',
        scope : {
            callFunction: "=call",
        }
    };
});

现在您可以在 page.html 中添加指令。它被定义了。不要忘记添加函数 ;).

<test call="callFunction"></test>

不要忘记添加 include 项目中的所有文件,现在可以正常工作了!

您是否忘记传递范围 test="test"

<dir1 test="test" ng-show="showdir1">

</dir1>

<dir2 test="test" ng-show="showdir2">

</dir2>