如何在 Angular 1.5 组件中等待绑定(没有 $scope.$watch)

新手上路,请多包涵

我正在编写一个 Angular 1.5 指令,我遇到了一个令人讨厌的问题,试图在绑定数据存在之前对其进行操作。

这是我的代码:

 app.component('formSelector', {
  bindings: {
    forms: '='
  },
  controller: function(FormSvc) {

    var ctrl = this
    this.favorites = []

    FormSvc.GetFavorites()
    .then(function(results) {
    ctrl.favorites = results
    for (var i = 0; i < ctrl.favorites.length; i++) {
      for (var j = 0; j < ctrl.forms.length; j++) {
          if (ctrl.favorites[i].id == ctrl.newForms[j].id) ctrl.forms[j].favorite = true
      }
     }
    })
}
...

如您所见,我正在进行 AJAX 调用以获取收藏夹,然后根据我绑定的表单列表对其进行检查。

问题是,甚至在填充绑定之前就已经实现了承诺……所以当我运行循环时,ctrl.forms 仍然未定义!

如果不使用 \(scope.\)watch(这是 1.5 组件的一部分),我如何等待绑定完成?

原文由 tcmoore 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 269
2 个回答

您可以使用 新的生命周期挂钩,特别是 $onChanges ,通过调用 isFirstChange 方法来检测绑定的第一次更改。 在此处 阅读更多相关信息。

这是一个例子:

 <div ng-app="app" ng-controller="MyCtrl as $ctrl">
  <my-component binding="$ctrl.binding"></my-component>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular.js"></script>
<script>
  angular
    .module('app', [])
    .controller('MyCtrl', function($timeout) {
      $timeout(() => {
        this.binding = 'first value';
      }, 750);

      $timeout(() => {
        this.binding = 'second value';
      }, 1500);
    })
    .component('myComponent', {
      bindings: {
        binding: '<'
      },
      controller: function() {
        // Use es6 destructuring to extract exactly what we need
        this.$onChanges = function({binding}) {
          if (angular.isDefined(binding)) {
            console.log({
              currentValue: binding.currentValue,
              isFirstChange: binding.isFirstChange()
            });
          }
        }
      }
    });
</script>

原文由 Cosmin Ababei 发布,翻译遵循 CC BY-SA 3.0 许可协议

我有一个类似的问题,我这样做是为了避免在我要发送的值准备好之前调用组件:

 <form-selector ng-if="asyncValue" forms="asyncValue" ></form-selector>

原文由 Ced 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题