2

我有以下格式,其中我有一个全局组件,其中包含 3 个嵌套组件,这些组件基于给定的路由激活:

  $stateProvider
    .state('create-goal', {
      url: '/create-goal',
      component: 'createGoal',
      redirectTo: 'create-goal.step-1'
    })
    .state('create-goal.step-1', {
      url: '/step-1',
      component: 'step1'
    })
    .state('create-goal.step-2', {
      url: '/step-2',
      component: 'step2'
    })
    .state('create-goal.step-3', {
      url: '/step-3',
      component: 'step3'
    });

在主create-goalhtml 文件中,我有以下内容:

  <ui-view goal="$ctrl.goal"
           goalInfo="$ctrl.goalInfo"
           processStep1="$ctrl.processStep1">
  </ui-view>

goal和很好用goalInfo,因为它们是一种数据绑定方式的数据。但是,当我想传递一个函数时,例如processStep1计算某些操作step-1等等,step-1即使goalandgoalInfo执行了,该函数也不会出现在组件中。

export default {
  name: 'step1',
  restrict: 'E',
  bindings: {
    goal: '<',
    processStep1: '&'
  },
  template,
  controller
};

想法?

4

1 回答 1

0

有几种方法可以做到这一点。

  • 使用 $parent 访问函数(我建议不要这样做,因为它是相对的并且可能会导致问题
  • 根据您的用例,使用 '=function' 或 '&function' 使用属性将其传递到每个子函数中
  • 在可以在任何地方注入的辅助服务中设置函数。如果您打算大量使用它,并且如果它只是用于数据操作,那么它确实属于服务,以避免臃肿的控制器。
  • 最后一种方法是使用模型。如果它是在某种类型的对象(例如可以轻松建模的用户)上运行的函数,这将是很好的。例如 .save 或 .update 函数。

https://docs.angularjs.org/guide/directive http://fdietz.github.io/recipes-with-angular-js/controllers/sharing-code-between-controllers-using-services.html https:// www.sitepoint.com/tidy-angular-controllers-factories-services/ http://www.webdeveasy.com/angularjs-data-model/

于 2017-03-30T01:03:28.923 回答