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

tee*_*ink 29 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"
        }
    }
  }
});
Run Code Online (Sandbox Code Playgroud)
<ng-form-field label="First Name" type="text"></ng-form-field>
Run Code Online (Sandbox Code Playgroud)

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

zim*_*zim 30

我已经使用$ 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>
Run Code Online (Sandbox Code Playgroud)

指示:

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);
        }
    };
}]);
Run Code Online (Sandbox Code Playgroud)

  • 很好的举动,Zim!只是略微简化:$ templateCache在链接函数中可用,因此您不需要getTemplate函数 (3认同)
  • 这不适用于`replace:true`指令. (3认同)

now*_*owk 17

有类似的需要.$compile做的工作.(不完全确定这是否是"THE"方式,仍然通过角度工作我的方式)

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

有一点要注意(根据我的例子),我的一个要求是,type一旦你点击保存模板将根据属性改变,模板是非常不同的.但是,您获得数据绑定,如果需要新模板,则必须重新编译.

  • 答案应该包括完整的示例和代码,而不是最后被破坏链接的链接. (3认同)

Aqu*_*jet 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);
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

它可以像这样使用:

<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>
Run Code Online (Sandbox Code Playgroud)


use*_*353 5

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

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