如何在Angular指令中传递参数给函数

How to pass parameters to a function within an Angular directive?

本文关键字:参数 函数 Angular 指令      更新时间:2023-09-26

在AngularJS指令中,我触发了一个回调函数,它需要访问一个已经注入的指令级对象。

我使用了一个KendoUI模板函数,但是我认为这更多的是关于作用域而不是函数的问题。

指令:

app.directive('projectEditorGrid', function (dataSourceFactory) {
    var dataSourceFactory = new dataSourceFactory("/odata/ProjectEditor");
    return {
        link: function ($scope, $element, $attrs) {
            $element.kendoGrid({
                dataSource: dataSourceFactory.projects(),
                pageable: true,
                height: 400,
                toolbar: ["create"],
                columns: [
                            { field: "WebsiteName", editable: true, width: 190, title: "Project Name", validation: { required: { message: "Project name is required" } } },
                            { field: "WebsiteNotes", title: "Project Notes" },
                            { field: "WebsiteGUID", title: "Project API ID", editable: false },
                            { field: "DefaultContentType", title: "Default Content Type", width: "160px", editor: defaultContentTypeDropDownEditor, template: "#=ContentTypes.Descriptions#" },
                            { command: ["edit", "destroy"] }
                ],
                editable: "inline"
            });
            function defaultContentTypeDropDownEditor(container, options) {
                console.log(container + " : " + options);
                var dataSourcFactory = dataSourceFactory("/odata/ContentType");
                var dsContentTypes = dataSourceFactory.contentTypes();  // returns a kendo.data.DataSource() object
                $('<input required data-text-field="Description" data-value-field="ContentTypeId" data-bind="value:' + options.field + '"/>')
                    .appendTo(container)
                    .kendoDropDownList({
                        autoBind: false,
                        dataSource: dataSourceFactory.contentTypes()
                    }); // kendoDropDownList
            }
        }
    }
});

dataSourceFactory被注入到指令中,并成功用于显示数据。

当行编辑被触发时,defaultContentTypeDropDownEditor被调用,其默认参数为container, options。如果我可以传递dataSourceFactory到这个函数,我将被设置,但不清楚如何从激活调用完成这一点。

options:

Object {field: "DefaultContentType", editor: function, model: n.extend.o}
editor: function defaultContentTypeDropDownEditor(container, options) {
field: "DefaultContentType"
model: n.extend.o
__proto__: Object

container:

[<td role=​"gridcell" data-container-for=​"DefaultContentType">​</td>​]

可以看到,dataSourceFactory在函数级别是可见的(注入到指令中),但是不能从defaultContentTypeDropDownEditor中访问。有人能解释一下如何做到这一点吗?

被注入的对象是dataSourceFactory。通过将初始化重命名为dataSourceFactory1,并将函数回调对它的使用重命名为dataSourceFactory2,我能够使其工作。

感谢Nikos为我指出了正确的方向。