【问题标题】:AngularJS directive passing dynamic ui-srefAngularJS指令传递动态ui-sref
【发布时间】:2019-09-06 04:49:12
【问题描述】:

我在一个大型项目中使用旧的 AngularJS 1.5.11,我正在尝试使用指令清理我的模板。

我有一个编辑按钮指令,我想在其中传递 ui-sref,但是当我这样做时出现错误

Error: [$parse:syntax] Syntax Error: Token '}' not a primary expression at column 6 of the expression [{id: }] starting at [}].

这是我的指令

editButton = ->

  return {
    restrict: 'EA',
    scope: {
      sref: "@"
    },
    template: '
    sref = {{sref}}
      <button id="edit-btn"
              class="mds__button -blue"
              ui-sref={{sref}}>
        <i class="fa fa-edit"></i> Edit
      </button>
    '
  }

angular
  .module('myApp')
  .directive('editButton', editButton)

这就是我的称呼

<edit-button sref="job_edit({id: {{job.id}}})" />

在我的模板中,我显示了 sref,它已正确打印出来,但按钮不喜欢 ui-sref。

更新

我让它工作了,但是重构它会很好,所以我传递了 job_edit({id: job.id}) 属性并且它工作了。

指令;

editButton = ->

  return {
    restrict: 'EA',
    scope: {
      model: "@"
      item: "="
    },
    template: '
      <button id="edit-btn"
              class="mds__button -blue"
              ui-sref="{{model}}_edit({id: item.id})">
        <i class="fa fa-edit"></i> Edit
      </button>
    '
  }

angular
  .module('myApp')
  .directive('editButton', editButton)

在我的模板中调用它;

<edit-button model="job" item="job" />

【问题讨论】:

    标签: angularjs angularjs-directive angular-ui-router coffeescript


    【解决方案1】:

    你不能在 Angularjs 模板中创建 sref = {{sref}}

    当您在指令的 scope 对象上声明 sref 时,这意味着您的指令将获得一个带有 sref 属性的隔离作用域,并将值作为属性传递给指令。

    此声明几乎没有可能的值,例如@=&amp;

    1. @ 用于插值,这意味着无论何时将值传递给属性,都需要传递一些插值
    <edit-button sref="{{somethingAvailableOnParentScope}}" />
    
    1. = 2路数据绑定,需要传递一些表达式
    <edit-button sref="somethingAvailableOnParentScope" />
    
    1. &amp; 绑定一个函数,用于将“指针”传递给函数。 (与我们的案例无关)

    综上所述,我们希望将job_edit 调用的值传递给我们的指令,因此我们需要使用=

    editButton = () => ({
        restrict: 'EA',
        scope: {
          sref: "="
        },
        template: '
          <button id="edit-btn"
                  class="mds__button -blue"
                  ui-sref="sref">
            <i class="fa fa-edit"></i> Edit
          </button>
        '
      });
    
    angular
      .module('myApp')
      .directive('editButton', editButton)
    

    而且用法会是这样的:

    <edit-button sref="job_edit({id: job.id})" />
    

    【讨论】:

    • 我只是使用 sref = {{sref}} 在屏幕上显示变量。
    • 你得到了什么?
    猜你喜欢
    • 1970-01-01
    • 2014-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多