我们有一个大模型,ng-repeat 需要几秒钟的时间将模型中的所有项目绑定到表单。我们想在发生这种情况时展示一个微调器。绑定完成时是否会触发某些事件,以便我们知道何时隐藏微调器?
4 回答
Plunkr:http ://plnkr.co/edit/GzzTW4?p=preview
在微调器上使用ng-show
如果您使用的是 1.2,请使用ng-if
<div ng-controller="Ctrl">
<div ng-show="complete">Complete={{complete}}</div>
<div class="thing" ng-repeat="thing in things" my-post-repeat-directive>
thing {{thing}}
</div>
</div>
在您的指令中使用 $last 来确定渲染是否完成,然后更改您定义了 ng-show/ngif 的变量。
function Ctrl($scope) {
$scope.complete=false;
$scope.doComplete = function() {
$scope.complete = true;
}
$scope.things = [
'A', 'B', 'C'
];
}
angular.module('myApp', [])
.directive('myPostRepeatDirective', function() {
return function(scope, element, attrs) {
if (scope.$last) {
scope.$eval('doComplete()');
}
};
});
在这种情况下,我将$timeout服务与 Angular ui 路由器触发的$viewContentLoaded事件混合使用(如果您使用 ui 路由器):
关于 $timeout :
该服务只是 $timeout 服务的简单装饰器,它添加了“flush”和“verifyNoPendingTasks”方法。
关于 $viewContentLoaded
在 DOM 渲染后,视图加载后触发。视图的“$scope”会发出事件。
我的个人用例是让 paymentForm 动态生成其隐藏输入(使用我通过 ng-bind-html 插入的 HTML 数据计算服务器端)并提交到支付网关:
$scope.$on('$viewContentLoaded', function() {
$timeout(function () {
$scope.paymentForm.submit();
});
});
仅供参考,在上面的代码示例中,.submit() 是与表单一起使用的自定义指令中的一个函数,以便能够自动提交表单。
朱利安
您可以监视$last
项目编译/链接功能,并将自定义事件触发到范围
为此,我通常使用 ng-show="submitting" 在您的视图中创建一个微调器 div。然后在加载数据时,将 $scope.submitting 设置为 'false' 显示微调器已隐藏。
<!-- In your HTML -->
<div class="spinner" ng-show="submitting">
<div ng-repeat="p in people">
{{p.name}}
</div>
//In Javascript
$scope.submitting = true;
$scope.load_data = function(){
$http.get('/api/route')
.then(function(success){
$scope.submitting = false;
},function(error){
console.log(error);
});
}
我希望这会有所帮助