angularjs - 如何在 AngularJS 中使用动态模板创建指令?

标签 angularjs angularjs-directive

如何使用动态模板创建指令?

'use strict';

app.directive('ngFormField', function($compile) {
return {
    transclude: true,
    scope: {
        label: '@'
    },
    template: '<label for="user_email">{{label}}</label>',
    // append
    replace: true,
    // attribute restriction
    restrict: 'E',
    // linking method
    link: function($scope, element, attrs) {
        switch (attrs['type']) {
            case "text":
                // append input field to "template"
            case "select":
                // append select dropdown to "template"
        }
    }
  }
});

<ng-form-field label="First Name" type="text"></ng-form-field>

这就是我现在所拥有的,它可以正确显示标签。但是,我不确定如何在模板中附加额外的 HTML。或者将 2 个模板合并为 1 个。

最佳答案

我已经使用 $templateCache 来完成类似的事情。我将几个 ng 模板放在一个 html 文件中,我使用指令的 templateUrl 引用该文件。这确保 html 可用于模板缓存。然后我可以简单地通过 id 选择来获得我想要的 ng-template。

模板.html:

<script type="text/ng-template" id=“foo”>
foo
</script>

<script type="text/ng-template" id=“bar”>
bar
</script>

指示:
myapp.directive(‘foobardirective’, ['$compile', '$templateCache', function ($compile, $templateCache) {

    var getTemplate = function(data) {
        // use data to determine which template to use
        var templateid = 'foo';
        var template = $templateCache.get(templateid);
        return template;
    }

    return {
        templateUrl: 'views/partials/template.html',
        scope: {data: '='},
        restrict: 'E',
        link: function(scope, element) {
            var template = getTemplate(scope.data);

            element.html(template);
            $compile(element.contents())(scope);
        }
    };
}]);

关于angularjs - 如何在 AngularJS 中使用动态模板创建指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14862315/

相关文章:

javascript - AngularJS 最佳实践 - 具有多种方法的工厂

javascript - AngularJs 中的函数问题

javascript - Angularjs 路由到 # 导致问题

javascript - AngularJS - 依赖下拉列表 : storing one value in model, 使用其他作为下一个下拉列表的来源

angularjs - 如何使用 AngularJS 限制输入的值?

javascript - 如何使 templateUrl 为 null 或未定义或空字符串的指令

javascript - 如何在 Safari 中显示保存文件对话框?

javascript - AngularJS 指令属性从 Controller 访问

angularjs - 从 ng-click 获取原始元素

javascript - 当用户键入时自动将格式添加到输入字段