我有以下标记:
<div class="row" loader="loader" address-book>
<!-- Loading complete - this should show result -->
<div loader-success></div>
<!-- Loading failed - this should show some error -->
<div loader-failure>Failure</div>
</div>
这address-book
是主要的应用,而loader
仅仅是在页面加载时显示动画。地址簿的内容将进入loader-success
,并且失败消息(即,如果找不到内容)将进入内部loader-failure
。
所以我的想法是使用以下指令:
app.directive('loader', function($compile, $timeout)
{
return {
restrict: 'AE',
scope: {
loader: '&'
},
transclude: true,
template:
'<div class="row" ng-if="loading">' +
' <div class="small-15 columns text-center">' +
' <i class="fa fa-spin fa-circle-o-notch"></i>' +
' </div>' +
'</div>' +
'<div ng-transclude></div>',
link: function(scope, element, attrs)
{
scope.loading = true;
scope.failure = false;
scope.success = false;
scope.$watch('loader', function(fn) {
if (_.isFunction(fn)) {
scope.loader()
.then(function(){
scope.success = true;
scope.loading = false;
scope.$safeApply();
})
.catch(function() {
scope.failure = true;
scope.loading = false;
scope.$safeApply();
});
}
});
}
};
});
那套scope.loader
的诺言在哪儿?在地址簿尝试获取内容后,将解决/拒绝承诺。$q
address-book
对于成功/失败模块,我有:
app.directive('loaderFailure', function()
{
return {
restrict: 'AE',
link: function(scope, element, attrs)
{
element.hide();
scope.$watch('failure', function(value) {
if (_.isTrue(value)) {
element.show();
}
});
}
};
});
app.directive('loaderSuccess', function()
{
return {
restrict: 'AE',
link: function(scope, element, attrs)
{
element.hide();
scope.$watch('success', function(value) {
if (_.isTrue(value)) {
element.show();
}
});
}
};
});
然而,由于在隔离范围loader
,这两个孩子的范围loader-success
,并loader-failure
不再能读取父的。我不能使用$compile
on,loader
因为那样会把范围从地址簿的应用程序中删除。
我能做些什么?
您可以使用事件。如果您想将一些日期从孩子发送给父母使用$scope.$emit
。
从父母到孩子$scope.$broadcast
-可能会对绩效产生负面影响
当您要在松散耦合的组件之间进行通信时,使用事件是一种很好的方法。
查看有关事件的更多信息:
https://docs.angularjs.org/api/ng/type/ $ rootScope.Scope#$ emit
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句