【问题标题】:Dynamic templates rendered using directive scope variables使用指令范围变量呈现的动态模板
【发布时间】:2015-01-03 16:58:27
【问题描述】:

试图找到一种方法来根据 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. 您能否访问动态加载的指令模板属性中的范围变量?我似乎只能对它们进行硬编码,因为如果解析,绑定不会在指令之前设置。

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

【问题讨论】:

标签: javascript angularjs angularjs-directive


【解决方案1】:

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

Demo

<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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多