在AngularJS中动态加载外部模板

时间:2015-02-16 17:32:20

标签: angularjs angularjs-directive

我试图在AngularJS中构建一个可编辑的表组件。我希望它工作的方式是,当用户单击特定行上的“编辑”按钮时,该行将替换为"编辑模板"包含绑定到模型的输入字段。您可以在此Plunker中查看我的进度。

我使用自定义指令允许我定义一个包含可编辑行的表,如下所示:

<table ng-controller="peopleController as peopleCtrl">
  <tr editable-row edit-model="person" edit-tmpl="'person-editor.html'"  ng-repeat="person in peopleCtrl.people">
    <td>{{person.name}}</td>
    <td>{{person.age}}</td>
    <td>
      <button>Edit</button>
    </td>
  </tr>
</table>

在editable-row指令的链接功能中,我正在创建&#34;编辑模板&#34;作为一个html字符串并使用$ compile将表达式绑定到指令范围。我想做的不是在链接函数中硬编码html,而是从从指令&#34; edit-tmpl&#34;引用的外部文件中加载模板。属性。注意:为指令设置templateUrl不会起作用,因为我只想在用户单击编辑按钮时加载模板并将其注入DOM。

我的问题有两个:

1)如何从&#34; edit-tmpl&#34;引用的模板文件中加载html。我的指令的Link函数中的属性?

2)由于我是Angular的新手,我想知道我的方法是否符合AngularJS的方式?从角度设计的角度来看,通过像这样的属性在HTML中指定编辑模板然后加载到指令的链接函数中是否是一个好主意,还是有一种我缺少的更好的方法?

1 个答案:

答案 0 :(得分:0)

app.directive('editableRow', function($compile){
  return{
    restrict:'A',
    replace:true,
    scope: {editModel: '='},


    link: function(scope, element, attr){
      element.find('button').on('click', function(){

            var htmlText = '<div ng-include="{{attr.editTmpl}}"></div>';

             OR

            var htmlText='<div ng-include src="{{attr.editTmpl}}"></div>';

            // I don't know which would work for you. but this is the way to add dynamic template to your directive by just passing appropriate path of template to attr.editTmpl attribute;

        var editTmpl = angular.element($compile(htmlText)(scope));
        element.replaceWith(editTmpl);
      });
    }
  };
});

但我只是怀疑你的指示。在这里你使用replaceWith方法(它将你的模板替换为现有的一个) 但是如何在连续完成编辑后获得原始模板或ROW?我想看到它的兄弟。

相关问题