【问题标题】:Angular 1.5 Component Bindings: Check if Callback is PresentAngular 1.5 组件绑定:检查回调是否存在
【发布时间】:2016-12-18 10:00:14
【问题描述】:

我有一个简单的 contactList 组件,它有 2 个绑定:contactsonRemove

  • contacts 只是要显示的联系人数组
  • onRemove 是回调函数
app
  .component('contactList', {
    template: 
      `<div ng-repeat="c in $ctrl.contacts">
         {{c.name}}
         <div ng-click="$ctrl.onRemove({contact: c})">Remove</div>
       </div>`,
    bindings: {
      contacts: '<',
      onRemove: '&'
    },
    controller: function() {}
  })

我在我的应用程序中多次使用这个组件。 onRemove 回调的行为可能会有所不同,具体取决于 在哪里 contactList 组件被使用。示例:

  • contactMainView(= 组件)使用contactList 组件显示搜索栏和结果联系人列表。 onRemove 将从数据库中删除联系人。

  • groupMembersView 使用contactList 组件显示属于给定组的所有联系人。 虽然不会设置onRemove,但此处应该无法删除联系人。


想法:

首先我想,我可以使用ng-if="$ctrl.onRemove",但这不起作用,因为onRemovecontactList 组件中绝不是undefinedconsole.log(this.onRemove) 总是打印:function(locals) { return parentGet(scope, locals); }

当然,我可以使用另一个 showRemove: '@' 绑定,但在我看来这并不 DRY


您有什么想法或更好的解决方案来完成工作吗?

【问题讨论】:

    标签: angularjs angularjs-directive angularjs-components angularjs-bindings


    【解决方案1】:

    最简单的方法是检查属性是否已定义。在你的控制器中注入$attrs 然后你可以这样做:

    if( $attrs.onRemove ) { //Do something }
    

    使用&amp; 绑定角度将包装函数,以保持对传递方法的原始$scope 的引用,即使未定义。

    【讨论】:

      【解决方案2】:

      对组件执行 onRemove 函数允许获取函数是否传入参数。所以你可以使用 ng-if="$ctrl.onRemove()"

      component('contactList', {
      template: 
        `<div ng-repeat="c in $ctrl.contacts">
           {{c.name}}
           <div ng-click="$ctrl.onRemove()({contact: c})" ng-if="$ctrl.onRemove()">Remove</div>
         </div>`,
      bindings: {
        contacts: '<',
        onRemove: '&'
      },
      controller: function() {
        console.log(this.onRemove);
        console.log(this.onRemove());
      }
      })
      

      【讨论】:

      • console.log(this.onRemove()); 在我将某些函数传递给on-remove="..." 时在代码中的某处抛出异常,但在未定义时会打印undefined
      • 请问如何定义回调函数绑定?
      • 请看这篇文章,它回答了你的问题stackoverflow.com/questions/18378520/…
      【解决方案3】:
      猜你喜欢
      • 2017-02-20
      • 2023-03-09
      • 2016-12-15
      • 2016-09-10
      • 1970-01-01
      • 2016-09-12
      • 1970-01-01
      • 2017-05-10
      • 2016-07-03
      相关资源
      最近更新 更多