javascript - AngularJS:当前指令实现直接使用变量中的模板,我有机会在这里使用 templateUrl 吗?

标签 javascript angularjs angularjs-directive angularjs-scope

我当前的指令实现可能无法使用 templateUrl:

  1. 我将模板存储在一些变量中
  2. 有一个函数 getTemplate,它带有一个参数来决定通过 switch 语句返回哪个变量
  3. 然后像这样使用返回的变量:

我的链接器功能:

var linker = function(scope, element, attrs){
    scope.$watch('networkCalled', function(value){
        if(value){
            // the below getTemplate returns for example: someTplVariable; 
            // which holds the HTML markup
            element.html( getTemplate(value) );
            $compile( element.contents() )(scope);
        }
    });
}

return {
    restrict: "A",
    replace: true,
    link: linker,
    scope: {
        content: "=",
        networkCalled: "="
    }

我有机会在这里使用 templateUrl 功能吗?我这里有多个模板,因此我想将它们移至单独的文件中。

另一方面,如果无法使用 templateUrl,那么建议使用另一种方法,该方法仍然使我能够动态设置模板,但通过 templateUrl。

当然,如果您需要更多代码,请告诉我

最佳答案

您可以在这里做一些漂亮的事情来通过将模板设置为 ng-include 并使用 2 路绑定(bind)变量作为其 url 来获取动态模板加载:

@note 我通常会将此链接器代码放入 Controller 中以获取 url 变量上的自动摘要循环

var linker = function(scope, element, attrs){
//set default url. 
scope.url = getTemplate(<default-value>);
scope.$watch('networkCalled', function(value){
    if(value){
        // set url to my current template. (may need $apply())
        scope.url = getTemplate(value);
    }
});

}

return {
restrict: "A",
replace: true,
link: linker,       //dynamically include html from url var
template: "<div ng-include="url"></div>
scope: {
    content: "=",
    networkCalled: "="
}

关于javascript - AngularJS:当前指令实现直接使用变量中的模板,我有机会在这里使用 templateUrl 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23730760/

相关文章:

php - 获取 php 变量并将其传递到 jQueryUI 对话框

javascript - 从控制台运行用户脚本时未定义函数

javascript - 在 React 中使用泛型键入 defaultProp 箭头函数方法

node.js - 将 PDF 文件从 AngularJS 发送到 NodeJS

javascript - 使用 JsDoc3 创建 AngularJS 文档时出现问题

javascript - 为什么浏览器在经过身份验证的 XMLHttpRequest 之后不重用授权 header ?

javascript - 为什么angularjs ng-repeat不起作用

javascript - 实时调试 Web 客户端

javascript - 将 angularjs 指令添加到 native html 元素(输入文本、div、span 等)?

css - 带有 css 的 Angular HTML 预览