javascript - 如何在指令范围内设置值

标签 javascript angularjs angularjs-directive

我有多个几乎相同的 AngularJS 指令 - 只有两个不同之处:模板 URL 和链接函数中的一个元素。对于每个指令,两者都是常量。因此,为了简单起见,它是这样的:

app.directive("myDirective", [function() {
    return {
        templateUrl: "this/path/changes.html",
        scope: true,
        link: function(scope, element, attrs) {
            var veryImportantString = "this_string_changes";
            // a few dozen lines of code identical to all directives
        }
    };
}]);

现在,将链接功能移动到一个普遍可用的地方是显而易见的。对我来说不太明显的是如何在范围内设置“非常重要的字符串”(或以其他方式将其传递给指令)而不在 HTML 中声明它。

这是我尝试过的。

app.directive("myDirective", [function() {
    return {
        templateUrl: "this/path/changes.html",
        scope: {
            veryImportantString: "this_string_changes"
        },
        link: someCommonFunction
    };
}]);

不,显然范围配置不会从任何人那里获取值。我可以绑定(bind)来自 HTML 属性的值,但这正是我不想做的。

也试过这个:

app.directive("myDirective", [function() {
    return {
        templateUrl: "this/path/changes.html",
        veryImportantString: "this_string_changes",
        scope: true,
        link: function(scope, element, attrs) {
            var veryImportantString = this.veryImportantString;
        }
    };
}]);

但是,很遗憾,然后调用链接函数时将 this 设置为其他内容。

我认为这可能有效:

app.directive("myDirective", [function() {
    return {
        templateUrl: "this/path/changes.html",
        scope: true,
        compile: function(element, attrs) {
            // no access to the scope...
            attrs.veryImportantString = "this_string_changes";
            return someCommonFunction;
        }
    };
}]);

但是,我也不是 100% 确定这就是我想要的,因为它是一种肮脏的解决方法。

我还有哪些其他选择?

最佳答案

我设计了一种完全不同的方法:使用类似工厂的函数来生成指令。

var factory = function(name, template, importantString) {
    app.directive(name, [function() {
        return {
            scope: true,
            templateUrl: template,
            link: function(scope, element, attrs) {
                var veryImportantString = importantString;
                // directive logic...
            }
        };
    }]);
};

然后,为了创建单独的指令,我只需调用:

factory("myDirective", "/path/to/template.html", "important");
factory("myDirective2", "/path/to/template2.html", "important2");

关于javascript - 如何在指令范围内设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22686624/

相关文章:

javascript - 从 C# 中的输出流返回文本

javascript - Angular : Directive transcluded scope lost

javascript - Angular Directive(指令)和 ng 类

javascript - 调整 Canvas 大小的后果

javascript - Angular js 两种方式数据绑定(bind)仅适用于 apply

javascript - 同时添加两个元素

javascript - 链式 promise 和原型(prototype) `this`

javascript - 输入标签不适用于 Angular Directive(指令)( Bootstrap )

javascript - 在其他 javascript 框架模板中运行 Angular 指令

javascript - 从浏览器执行applescript