使用注入属性将html块封装在指令内的最佳方法

时间:2014-10-08 21:45:00

标签: angularjs angular-directive

<div ng-repeat="post in posts">
  <a e-form="review_link" ng-click="review_link.$show()" editable-text="post.review_link" buttons="no" blur="submit" e-placeholder="Leave blank to use default value">{{ post.url }}</a>
  <a e-form="title" ng-click="title.$show()" editable-text="post.title" buttons="no" blur="submit" e-placeholder="Leave blank to use default value">{{ post.title }}</a>
  <a e-form="author" ng-click="author.$show()" editable-text="post.author" buttons="no" blur="submit" e-placeholder="Leave blank to use default value">{{ post.author }}</a>
  <!-- other different widgets -->
</div>

我试图做类似的事情:

<div ng-repeat="post in posts">
  <custom-directive field="field" ng-repeat="field in ['review_link', 'title', 'author']"></custom-directive>
  <!-- other different widgets -->
</div>

和指令:

app.directive('customDirective', function() {
  return {
    restrict: 'E',
    scope: {
      field: '='
    },
    template: '<a e-form="{{field}}" ng-click="{{field}}.$show()" editable-text="post[{{field}}]" buttons="no" blur="submit" e-placeholder="Leave blank to use default value">{{ post.author }}</a>' 
  }
}

但我得到了编译语法错误

PD:我在示例中使用http://vitalets.github.io/angular-xeditable/#overview

1 个答案:

答案 0 :(得分:0)

ng-click="{{field}}.$show()"引起的语法错误。

将其更改为 ng-click="field.$show()"。你不需要ng-repeat

里面的花括号

此外,您似乎正在尝试从您的指令模板访问post(由于它未与指令共享,因此无法使用post - 范围是孤立的。)

该怎么办?将scope添加到scope: { field: '=', post: '=' }, ,如下所示:

field

将其传递给您的指令,就像使用<custom-directive field="field" post="post" ...

一样
{{1}}

示例:http://plnkr.co/edit/szDjDw3bnLtDSRr2O08H?p=preview