How to wait for binding in Angular 1.5 component (without $scope.$watch)(如何在 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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Angular 1.5 组件中等待绑定(没有 $scope.$watch)
基础教程推荐
- 如何添加到目前为止的天数? 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
