【问题标题】:Angular '&' Binding and parametersAngular '&' 绑定和参数
【发布时间】:2017-03-25 19:34:34
【问题描述】:

我正在尝试编写一个名为“foo”的组件——该组件带有一个标签,并显示“hello {{$ctrl.label}}”。它还会在点击时调用回调函数

<foo label="'bar'" callback="$ctrl.myCallback()"</foo>

到目前为止一切顺利。我的控制器确实得到了回调

所以现在我把这个元素放入一个 ng-repeat: <foo ng-repeat="item in $ctrl.items" label="item.label" callback="$ctrl.myCallback(item)></foo>

如何在组件中定义单击时要传回控制器的内容?该组件没有 item 传递给它,只有“标签”。

根据我的阅读,我需要说一些类似的话 this.callback({item: SomeObject});

我在这里有 2 个问题:1)组件如何知道它需要提供“item”键以及 2)组件如何知道 SomeObject 是什么?

我可以轻松地在另一个 ng-repeat 中重用该组件: <foo ng-repeat="order in $ctrl.orders" label="order.orderNum" callback="$ctrl.myCallback(order)></foo>

在这种情况下,组件如何知道将订单对象作为参数发送给点击回调函数?

【问题讨论】:

    标签: angularjs angular-components


    【解决方案1】:

    组件对它了解不多,你知道,你的单元测试知道,你的 e2e 测试知道(可能是),但组件只知道它有一个回调(带有命名参数)和一个属性及其way-binding,这就是绑定所需要的。此外,您不必从组件端传递任何东西,除非您从组件发送项目对象,否则,只需使用简单的$ctr.callback(),绑定将从ng-repeat 范围调用$parent.myControllerFunction(item) .

    使用&amp; 时,您可以根据您在模板上创建的掩码创建要从组件调用的委托方法。例如:

    <ANY ng-repeat="item in items" callback="myCallBack(item)">
    ...
    bindings: {
        callback: '&'
    }
    ...
    

    如果您从组件中调用它,如$ctrl.callback(),它将使用来自ng-repeat 范围的项目。但是,如果您想从组件发送它,那么您必须传递一个对象,该对象的名称是您在模板上使用的参数名称,例如 $ctrl.callback({ item: { name: 'foo'}}),以填充在 callback="myCallBack(item)" 上声明的参数。

    angular
      .module('mBoard', [])
      .component('widget', {
        bindings: {
          item: '=',
          callback: '&'
        },
        controller: function() {
    
          var $ctrl = this;
    
          $ctrl.save = function() {
            //$ctrl.callback();
            $ctrl.callback({ item: { name : $ctrl.item.name + '%%%%' }});
    
          }
        },
        templateUrl: 'template.html'
      })
      .controller('mBoardCtrl', function mBoardCtrl($interval, $scope) {
        $scope.items = [{name: 'uno'}, {name: 'dos'}, {name: 'tres'}];
        $scope.setItem = function(item) {
    
          console.log(item)
        }
      });
    
    /* https://docs.angularjs.org/guide/bootstrap */
    angular.bootstrap(document, ['mBoard']);
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.js"></script>
    <div ng-controller="mBoardCtrl ">
      <widget ng-repeat="item in items" item="item" callback="setItem(item)"></widget>
      <hr>
      <widget ng-repeat="item in items" item="item" callback="setItem('quatorze')"></widget>
    
    
      <!-- https://docs.angularjs.org/api/ng/service/$templateCache -->
      <script type="text/ng-template" id="template.html">
        <button type="button" ng-click="$ctrl.save()">{{ $ctrl.item.name }}</button>
      </script>
    </div>

    【讨论】:

    • 哦,我明白了。这就说得通了。我会试试看 - 谢谢!
    • @jmls 好的,我已经用更详细的解释和示例更新了我的答案,如果你想查看的话。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-27
    • 1970-01-01
    • 2014-01-18
    • 2018-09-18
    • 2018-03-19
    • 2012-12-02
    相关资源
    最近更新 更多