使用指令作用域变量呈现的动态模板

Dynamic templates rendered using directive scope variables

本文关键字:动态 指令 作用域 变量      更新时间:2023-09-26

试图找到一种方法,根据JSON文档中指定的Type变量,用不同的控件呈现表单。这个表单将根据用户输入生成,所以我们不知道需要呈现什么问题类型。我们将定义类型,但它们可以按照用户的任何顺序出现。

{
  "Name": "Getting to know you.",
  "Id": "870tVcee8irPLdhi14fSZw==",
  "Controls": [
      {
          "Type": "Text",
          "Label": "First Name",
          "Id": "vF4z8YcSlpJGsF9fDw5TpA==", 
          "Color": "FFFFFF",
          "Required": "True",
          "Validaion": "False",
          "ValidationRegEx": "",
          "ErrorText": ""
      },
      {
          "Type": "Picklist",
          "Label": "Last Name",
          "Id": "vF4z8YcSlpJGsF9fDw5TpA==",
          "Color": "#CCCCCC",
          "Required": "True",
          "Validaion": "False",
          "ValidationRegEx": "",
          "ErrorText": "",
          "PicklistVals": ["1","3","5"]
      }
   ]
}

指令需要读取控件类型,然后将其传递给指令,以确定要呈现的模板。

<div ng-repeat="control in section.Controls">
    <input-parser ele="{{control}}"></input-parser>
</div>  

app.directive('inputParser', function() {
    function getTemplate (control) {
        var template = '';
        switch(control.Type) {
            case 'Text':
                template = '<form style="color:' + control.Color + '">template2</form>';
                break;
            case 'Picklist':
                template = '<form style="color:' + control.Color + '">template2</form>';
                break;
        }
        return template;
    }
    return {
        restrict: "E",
        scope: {
            control: '@'
        },
        template: function() {
            return getTemplate(control));
        }
    }

两个问题:

  1. 您可以访问动态加载的指令的template属性中的作用域变量吗?我似乎只能硬编码它们,因为如果解析的话,绑定不会在指令之前设置。

  2. 这是呈现需要访问传递到指令中的信息的动态模板的好方法吗。我应该只访问根作用域而忘记作用域变量吗?

如果您的input-parser指令只是呈现表单,而不做任何其他操作,那么不如考虑使用ng-include,并将所有模板作为分部放置。

演示

<ng-include ng-repeat="control in section.Controls" src="control.type + '.html'"></ng-include>

但是,如果您的input-parser指令确实有某种行为,您希望在所有模板中共享,那么您可以使用上面的ng-include作为模板。

Javascript

  .directive('inputParser', function() {
    return {
      restrict: 'E',
      scope: {
        control: '='
      },
      template: '<ng-include src="''form'' + control.type + ''.html''"></ng-include>'
      // controller: function() {}, // attach your controller behaviour
      // link: function() {} // attach your element behaviour
    };
  });

HTML

<input-parser ng-repeat="control in section.Controls" control="control"></input-parser>