首页 > 代码库 > angular组件component无法传递数据的坑

angular组件component无法传递数据的坑

 问题:使用组件component时组件无法从外获取到绑定的数据

 先贴上官方component的介绍及demo地址:https://docs.angularjs.org/guide/component; 

将confirm-dialog.html插入到main.html页面,并将vm.agreemnt传入到confirm.dialog.html中

 

main.html

在此页面中使用cost-info来传输数据,将main.controller中的vm.agreement传递给cost-info ,on-cancel,on-agree用来绑定事件

<div class="container">
<confirm-dialog cost-info = ‘$ctrl.agreement‘ on-cancel=‘$ctrl.cancleRentalBicycleHandler()‘ on-agree=‘$ctrl.returnBicycleHandler()‘> </confirm-dialog>
</div>

cost-info:用来传输数据,将main.controller中的vm.agreement传递个cost-info

 main.controller

vm.agreement = {
  ‘name‘:‘会捕鼠的鱼‘,
  ‘age‘:‘18‘
}

function cancleRentalBicycleHandler(){ // do something } function returnBicycleHandler(){ // do something }

 confirm-dialog.html

<div class="dialog">
  <div class="weui-mask"></div>
  <div class="weui-dialog">
    <div class="weui-dialog__bd">description :{{ $ctrl.costInfo.name }}</div>
    <div class="weui-dialog__bd">bicycleCode :{{ $ctrl.costInfo.age}}</div>
    <div class="weui-dialog__ft">
      <span ng-click="$ctrl.cancelHandler()"  class="weui-dialog__btn weui-dialog__btn_default">再骑一会</span>
      <span ng-click=" $ctrl.agreeHandler() " class="weui-dialog__btn weui-dialog__btn_primary">确认还车</span>
    </div>
  </div>
</div>

  

 

 

confirm-dialog.component.js

在confirm-dialog的controller中进行绑定事件的处理

  angular.module(‘XXX‘).component(‘confirmDialog‘, {
    templateUrl: ‘confirm.dialog.html‘,
    controller: confirmDialogController,
    bindings:{
      costInfo:‘<‘,// ‘<‘数据单项传递,‘=’双向传递
      onCancel :‘&‘,// ‘&’绑定事件
      onAgree:‘&‘
    }
  });
  confirmDialogController.$inject = ‘$log‘];
  function confirmDialogController($log) {
    var vm = this;
    vm.cancelHandler = cancelHandler;
    vm.agreeHandler = agreeHandler;
    function cancelHandler() {
      vm.onCancel();
    }
    function agreeHandler(){
      vm.onAgree();
    }
  }

  component可以借鉴directive的使用方法.

使用component在binding中costInfo写法是这样的话,在main.html中应该使用cost-info,

使用component在binding中costinfo写法是这样的话,在main.html中应该使用costinfo,

 

angular组件component无法传递数据的坑