在使用依赖于绑定值完成初始化的子组件进行初始化之前,我很难找到一种让组件绑定在父作用域中稳定的好方法。
这是我的小提琴:https://jsfiddle.net/nLpd9bsq/2/
可能的解决方案:
1。使用$ onChanges()等待所有绑定稳定
在这个例子中,我们只有1个绑定,但是想象一下我们有一个带有3个绑定的组件,每个值都在父作用域中异步加载。尝试在子范围上同步初始化而不使用像promise这样的东西会很麻烦。
2。将“异步值”初始化移至服务
将初始化移动到Service并使用promise解析它,然后将此服务注入大写和小写组件。通过这样做,除了我们放弃组件绑定机制的事实之外,我们还将失去对appController中初始化的控制,并且需要额外的代码到服务中以防止两个组件发出相同的异步请求在它自己的初始化周期中,最后是重复的异步请求。
你有什么想法?你会使用哪种解决方案? 谢谢!
app.js
angular.module('app', [ ]);
angular
.module('app')
.controller('appController',function($scope, $timeout){
var $ctrl = this;
$timeout(function(){
$ctrl.value = 'Async value'
}, 1000);
})
.component('uppercase', {
bindings : {
stringVal : '<'
},
controller: function($scope){
this.$onChanges = function(obj){
/* Needed to wait initialization on the parent */
if(obj.stringVal.currentValue){
this.upperVal = this.stringVal.toUpperCase();
}
};
},
template : '<div>Uppercase value: {{$ctrl.upperVal}}</div>'
})
.component('lowercase', {
bindings : {
stringVal : '<'
},
controller: function($scope){
this.$onChanges = function(obj){
/* Needed to wait initialization on the parent */
if(obj.stringVal.currentValue){
this.upperVal = this.stringVal.toLowerCase();
}
};
},
template :'<div>Lowercase value: {{$ctrl.upperVal}}</div>'
});
app.html
<div ng-app="app" ng-controller="appController as $ctrl">
<uppercase data-string-val="$ctrl.value"></uppercase>
<lowercase data-string-val="$ctrl.value"></lowercase>
</div>
答案 0 :(得分:2)
我会将数据初始化移动到服务,并在数据可用或更新时发出事件。
您可以使用https://stackoverflow.com/a/36291681/217408来阻止重复请求。