What is the best way to pass functions between inner components in AngularJS 1.5?

空扰寡人 提交于 2019-12-04 03:00:23

It is not necessary to provide a wrapper function in the controller of your sub-components. By using bindings a function is automatically attached to the controller, which you can call directly from your template.

The only wrinkle is that this function takes an object, which contains the locals that will be made available to the expression in the outer template.

In this case the data variable in the outer template needs to be provided explicitly when call the the doSomething(locals) method.

angular.module('app', [])

.component('app', {
  controller: class AppController {
    doSomething (data) {
      console.log(data);
    }
  },
  template: `
    <sub-component do-something="$ctrl.doSomething(data)">
    </sub-component>
  `
})

.component('subComponent', {
    bindings: {
        doSomething: '&'
    },
    template: `
        <inner-component do-something="$ctrl.doSomething({data: data})">
        </inner-component>
    `
})

.component('innerComponent', {
    bindings: {
        doSomething: '&'
    },
    template: `
        <sub-inner-component do-something="$ctrl.doSomething({data: data})">
        </sub-inner-component>
    `
})

.component('subInnerComponent', {
  bindings: {
    doSomething: '&'
  },
  template: `
      <button ng-click="$ctrl.doSomething({data: 123})">Do Something</button>
  `
});

Here is a working Plunker : http://plnkr.co/edit/QQF9jDGf6yiewCRs1EDu?p=preview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!