AngularJS : 如何嵌入并同时具有隔离作用域和父作用域?

AngularJS : How to transclude and have both isolate scope and parent scope?

我有一个模式,其中许多项目类型是 "editable"。这意味着我有很多模板(每个可编辑项目类型一个)期望具有独特的字段,但具有通用功能(编辑、保存、取消编辑、删除等)。这些常用函数导致控制器上出现大量重复:saveeditcancel 等,以及非常重复的错误处理。

我考虑的一种处理方法是让每个控制器 "decorate" 本身(使用服务),但它也变得混乱。

我更喜欢指令,例如,'editable':

<form name="editGroup" editable>
   <div ng-show="editMode">
    <!-- lots of fields, e.g. -->
    <input type="text" ng-model="name"></input>
    <span ng-show="editGroup.name.$error.required">The name is required</span>

    <button type="submit" ng-click="save()">Save</button>
    <button ng-click="cancel">Cancel</button>
   </div>
   <div ng-show="!editMode">
    <!-- lots of text, e.g. -->
    <span>{{name}}</span>

    <button ng-click="edit()">Edit</button>
    <button ng-click="delete()">Delete</button>
   </div>
</form>

问题是所有的模型都来自 controller 范围,因为它们对于这个模板来说是唯一的,而重复的范围项目,比如函数 save() cancel() edit() delete() 全部来自指令隔离作用域。

我是,好吧,混合示波器,当然我无法提前知道哪些项目需要可用。所以如果我嵌入:

我这里做错了;更好(更清洁?)的方法是什么?

我设法通过回避 ng-transclude 并在 link 函数中进行自己的嵌入来解决这个问题。

下面相当于正常的ng-transclude

link: function (scope,element,attrs,ctrlr,transclude) {
   var sc = scope.$parent.$new();
   transclude(sc,function(clone,scope) {
      element.append(clone); // or however else you want to manipulate the DOM
   });
}

通过将函数 直接 添加到 transclude 子作用域中,我能够让一切正常工作,而不会弄乱父作用域,我真的不想这样做.

link: function (scope,element,attrs,ctrlr,transclude) {
   var sc = scope.$parent.$new();
   sc.editMode = false;
   sc.save = function() {
   };
   sc.edit = function () {
     sc.editMode = true;
   };
   // etc.
   transclude(sc,function(clone,scope) {
      element.append(clone); // or however else you want to manipulate the DOM
   });
}

两全其美!