How to create a directive with a dynamic template in AngularJS?

后端 未结 7 857
傲寒
傲寒 2020-12-02 14:45

How can I create a directive with a dynamic template?

\'use strict\';

app.directive(\'ngFormField\', function($compil         


        
7条回答
  •  情歌与酒
    2020-12-02 15:13

    You should move your switch into the template by using the 'ng-switch' directive:

    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:
                '
    ' + ' {{title}}:' + ' ' + ' ' + ' ' + ' ' + '
    ', restrict: 'E', replace: true, scope: { fieldType: "@", title: "@", name: "@", value: "@", options: "=", }, link: function($scope, $element, $attrs, form) { $scope.field = $scope; form.addField($scope); } }; });

    It can be use like this:

    
        
    User '{{!form.fields.email.value}}' will be a {{!form.fields.role.value}}

提交回复
热议问题