使用指令范围变量呈现的动态模板

时间:2014-11-07 00:42:16

标签: javascript angularjs angularjs-directive

尝试根据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. 这是一种渲染动态模板的好方法,这些模板需要访问传递给指令的信息。我应该只访问根范围并忘记范围变量吗?

1 个答案:

答案 0 :(得分:0)

如果您的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>