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

2022-01-21 00:00:00 angularjs javascript components

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

I'm writing an Angular 1.5 directive and I'm running into an obnoxious issue with trying to manipulate bound data before it exists.

这是我的代码:

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 调用以获取收藏夹,然后对照我的绑定表单列表检查它.

As you can see, I'm making an AJAX call to get favorites and then checking it against my bound list of forms.

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

The problem is, the promise is being fulfilled even before the binding is populated... so that by the time I run the loop, ctrl.forms is still undefined!

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

Without using a $scope.$watch (which is part of the appeal of 1.5 components) how do I wait for the binding to be completed?

推荐答案

你可以使用新的生命周期钩子,特别是 $onChanges,通过调用isFirstChange<检测绑定的第一次变化/代码>方法.在此处了解更多信息.

You could use the new lifecycle hooks, specifically $onChanges, to detect the first change of a binding by calling the isFirstChange method. Read more about this here.

这是一个例子:

<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>

相关文章