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
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
