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

时间:2013-02-13 20:17:35

标签: 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个。

7 个答案:

答案 0 :(得分:29)

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

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);
        }
    };
}]);

答案 1 :(得分:18)

有类似的需求。 $compile完成这项工作。 (不完全确定这是否是“THE”方式,仍然在我的方式通过角度)

http://jsbin.com/ebuhuv/7/edit - 我的探索测试。

有一点需要注意(根据我的示例),我的一个要求是,一旦单击保存,模板将根据type属性进行更改,并且模板非常不同。因此,您可以获得数据绑定,如果需要新模板,则必须重新编译。

答案 2 :(得分:8)

您应该使用“ng-switch”指令将交换机移动到模板中:

module.directive('testForm', function() {
    return {
        restrict: 'E',
        controllerAs: 'form',
        controller: function ($scope) {
            console.log("Form controller initialization");
            var self = this;
            this.fields = {};
            this.addField = function(field) {
                console.log("New field: ", field);
                self.fields[field.name] = field;
            };
        }
    }
});

module.directive('formField', function () {
    return {
        require: "^testForm",
        template:
            '<div ng-switch="field.fieldType">' +
            '    <span>{{title}}:</span>' +
            '    <input' +
            '        ng-switch-when="text"' +
            '        name="{{field.name}}"' +
            '        type="text"' +
            '        ng-model="field.value"' +
            '    />' +
            '    <select' +
            '        ng-switch-when="select"' +
            '        name="{{field.name}}"' +
            '        ng-model="field.value"' +
            '        ng-options="option for option in options">' +
            '        <option value=""></option>' +
            '    </select>' +
            '</div>',
        restrict: 'E',
        replace: true,
        scope: {
            fieldType: "@",
            title: "@",
            name: "@",
            value: "@",
            options: "=",
        },
        link: function($scope, $element, $attrs, form) {
            $scope.field = $scope;
            form.addField($scope);
        }
    };
});

可以这样使用:

<test-form>
    <div>
        User '{{!form.fields.email.value}}' will be a {{!form.fields.role.value}}
    </div>
    <form-field title="Email" name="email" field-type="text" value="me@example.com"></form-field>
    <form-field title="Role" name="role" field-type="select" options="['Cook', 'Eater']"></form-field>
    <form-field title="Sex" name="sex" field-type="select" options="['Awesome', 'So-so', 'awful']"></form-field>
</test-form>

答案 3 :(得分:3)

如果你想将AngularJs指令与动态模板一起使用,你可以使用这些答案,但这里有更强的专业合法语法。你可以使用templateUrl不仅可以使用单个值。您可以将它用作函数,它返回一个值为url 。该函数有一些参数,您可以使用它。

http://www.w3docs.com/snippets/angularjs/dynamically-change-template-url-in-angularjs-directives.html

答案 4 :(得分:2)

一种方法是在指令中使用模板函数:

...
template: function(tElem, tAttrs){
    return '<div ng-include="' + tAttrs.template + '" />';
}
...

答案 5 :(得分:1)

我成功解决了这个问题。以下是链接:

https://github.com/nakosung/ng-dynamic-template-example

具体文件为:

https://github.com/nakosung/ng-dynamic-template-example/blob/master/src/main.coffee

dynamicTemplate指令托管动态模板,该模板在范围内传递,托管元素与其他原生角元素一样。

scope.template = '< div ng-controller="SomeUberCtrl">rocks< /div>'

答案 6 :(得分:0)

我遇到过相同的情况,我的完整解决方案已发布here

基本上我以这种方式在指令中加载模板

var tpl = '' + 
    <div ng-if="maxLength" 
        ng-include="\'length.tpl.html\'">
    </div>' +
    '<div ng-if="required" 
        ng-include="\'required.tpl.html\'">
    </div>';

然后根据maxLengthrequired的值,我可以动态加载其中一个模板,如果需要,一次只能显示其中一个模板。

我说它有帮助。