gpt4 book ai didi

javascript - 在 typescript 中创建指令以显示 Angular 加载进度

转载 作者:行者123 更新时间:2023-11-27 22:48:44 25 4
gpt4 key购买 nike

我正在尝试在 Typescript 中创建指令,该指令将监视待处理的 $resource 请求。我只想要一个指令作为属性,该属性将与 index.html 中的 div 一起使用以显示加载进度。下面是我的指令代码。

module app.common.directives {

interface IProgressbarScope extends ng.IScope {
value: number;
isLoading: any;
showEl: any;
}

class Progressbar implements ng.IDirective {

static $inject = ['$http'];
static instance(): ng.IDirective {
return new Progressbar;
}
//transclude = true;
restrict = 'A';
replace = true;

link = function (scope: IProgressbarScope, elements: ng.IAugmentedJQuery, attrs: ng.IAttributes, $http: ng.IHttpService) {

debugger;
scope.isLoading = function () {
return $http.pendingRequests.length > 0;
};
scope.$watch(scope.isLoading, function (v) {
debugger
if (v) {
elements.addClass("hidediv")
} else {
elements.removeClass("hidediv");
}
});
}
}

angular.module('app')
.directive('progressbar', Progressbar.instance);
}

在Index.html中,使用如下:

 <div progressbar id="myProcess" name="myProcess">
// loading image
</div>

但是在指令中,$http 始终是未定义的。请注意,我没有直接使用 $http。我使用 $resource 服务来发出服务器端 api 请求。

最佳答案

$http 未定义的原因是,您试图从指令的 link 函数获取 $http 依赖项。基本上,链接函数的第四个参数代表 require Controller 。

理想情况下,您应该从 Progressbar 构造函数获取注入(inject)的依赖项实例。

class Progressbar implements ng.IDirective {
_http: ng.IHttpService; //defined _http variable
static $inject = ['$http'];
//asking for dependency here
static instance($http: ng.IHttpService): ng.IDirective {
this._http = $http; //get `$http` object assigned to `_http`
return new Progressbar;
}
//transclude = true;
restrict = 'A';
replace = true;

//removed dependency from here
link = function (scope: IProgressbarScope, elements: ng.IAugmentedJQuery, attrs: ng.IAttributes) {

//use arrow function here
scope.isLoading = ()=> {
return this._http.pendingRequests.length > 0;
};
//use arrow function here
scope.$watch(scope.isLoading, (v)=> {
if (v) {
elements.addClass("hidediv")
} else {
elements.removeClass("hidediv");
}
});
}
}

关于javascript - 在 typescript 中创建指令以显示 Angular 加载进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38226567/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com