创建跨模型和控制器使用的指令

Create directive to use across models and controllers

本文关键字:指令 控制器 模型 创建      更新时间:2023-09-26

我在我的应用程序中有非常类似的功能,用户可以输入标题和链接。

所以-我想我应该创建一个指令。然而,这个指令需要在各种控制器的上下文中使用。

例如,在my/contracts视图中,控制器是ContractsController,在提交时,ContractsController将发送一个API请求来保存合同。

但是在我的/meeting-notes视图中,控制器是MeetingNotesController,这将处理对不同端点的请求-根据客户端保存会议记录。

这是我的指令到目前为止: app.js

.directive('myprefixLinkAttachment', function($timeout) {
    return {
        restrict: 'A',
        templateUrl: '../partials/directives/link-attachment.html',
        scope: {},
        link: function link(scope, element, attrs) {
            $timeout(function() {
                console.log(scope.$parent);
                console.log(scope.title);
            }, 5000);
        }
    }
})

超时返回正确的值-我正在测试是否可以获得该值。

link-attachment.html

<md-input-container class="md-block" md-no-float flex="100" flex-gt-xs="66">
    <input ng-model="title" placeholder="Title...">
</md-input-container>
<md-input-container class="md-block" flex="100" flex-gt-xs="33">
    <input ng-model="link" placeholder="Title..." ng-keypress="CtrlNameHere.save($event)">
</md-input-container>

我从内部调用指令(在这个例子中)ContractsController -但这需要改变。

<div layout="column" layout-gt-xs="row" class="new-entry-line" myprefix-link-attachment>

总之-我想自由地使用指令,同时能够调用正确的控制器来处理CtrlNameHere.save()方法。

你还没问问题。我猜你想问的是,当你在不同控制器的作用域中使用相同的指令时,如何调用控制器的函数。

你需要做的就是把指令要调用的函数传递给它。

所以在你的指令中你需要接受一个controllerFn属性,像这样:

scope: {
    controllerFn: "="
}

使用指令时,将控制器的函数传递给它,如下所示:

<myprefix-link-attachment controller-fn="someControllerFunction">

最后在模板中,调用作用域中已有的函数:

ng-keypress="controllerFn($event)"