如何在Angular 1.5组件中等待绑定(没有$ scope。$ watch) [英] How to wait for binding in Angular 1.5 component (without $scope.$watch)

查看:55
本文介绍了如何在Angular 1.5组件中等待绑定(没有$ scope。$ watch)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个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>

这篇关于如何在Angular 1.5组件中等待绑定(没有$ scope。$ watch)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆