【问题标题】:Best way to encapsulate chucks of html inside directives with injected attributes使用注入属性在指令中封装 html 夹头的最佳方法
【发布时间】:2014-10-08 21:45:00
【问题描述】:
<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>

和 on 指令:

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

【问题讨论】:

  • 基本上,语法错误意味着语法有问题(冒号、大括号、括号、逗号、关键字、标记顺序)...发布特定的错误消息可能有助于追踪您的问题.

标签: angularjs angular-directive


【解决方案1】:

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

改成 ng-click="field.$show()"ng-repeat 内不需要花括号

此外,您似乎正在尝试从指令的模板访问post(这不起作用,因为它不与指令共享 - 范围是孤立的)。

怎么办?像这样将post 添加到scope

scope: {
  field: '=',
  post: '='
},

将它添加到您的指令中,就像您对 field 所做的那样:

<custom-directive field="field" post="post" ...

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

【讨论】:

    猜你喜欢
    • 2012-12-07
    • 1970-01-01
    • 2013-09-14
    • 1970-01-01
    • 1970-01-01
    • 2021-01-04
    • 1970-01-01
    • 2019-07-31
    • 2017-10-10
    相关资源
    最近更新 更多