我正在编写一个角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组件吸引力的一部分),如何等待绑定完成?
发布于 2016-02-25 22:18:38
您可以使用--新的生命周期挂钩,特别是$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>
发布于 2016-05-20 06:25:09
我有一个类似的问题,我这样做是为了避免调用组件,直到我要发送的值准备就绪为止:
<form-selector ng-if="asyncValue" forms="asyncValue" ></form-selector>发布于 2016-08-09 01:35:28
原海报上写着:
承诺甚至在装订之前就已经实现了.当我运行循环时,ctrl.forms仍未定义
从AngularJS 1.5.3开始,我们就有了生命周期钩,为了满足OP的问题,您只需要移动取决于$onInit()内部满足绑定的代码
$onInit() -在构造了元素上的所有控制器并初始化了它们的绑定之后(以及在该元素的指令的预-后链接函数之前)调用了每个控制器。这是一个为您的控制器放置初始化代码的好地方。
所以在这个例子中:
app.component('formSelector', {
bindings: {
forms: '='
},
controller: function(FormSvc) {
var ctrl = this;
this.favorites = [];
this.$onInit = function() {
// At this point, bindings have been resolved.
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;
}
}
}
});
}
}是的,有一个$onChanges(changesObj),但是$onInit()专门解决了最初的问题,即什么时候才能保证绑定已经解决。
https://stackoverflow.com/questions/35639435
复制相似问题