在打字稿中创建指令以显示角度加载进度 [英] Create directive in typescript to show loading progress in angular
问题描述
我正在尝试在Typescript中创建指令,该指令将监视未决的$ resource请求.我只需要一个指令作为属性,它将与index.html中的div一起使用以显示加载进度.下面是我的指令代码.
I am trying to create directive in Typescript which will keep watch on pending $resource requests. I want only one directive as an attribute which will be used with div in index.html to show loading progress. Below is my code for directive.
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中,其用法如下:
in Index.html, it is used as below:
<div progressbar id="myProcess" name="myProcess">
// loading image
</div>
但是在指令中,$ http始终是未定义的.请注意,我没有直接使用$ http.我使用$ resource服务进行服务器端api请求.
But in directive, $http is always undefined. Note that I am not using $http directly. I a using $resource service for making server side api requests.
推荐答案
未定义$http
的原因是,您正在尝试从指令的link
函数获取$http
依赖项.基本上,链接功能的第四个参数代表require
控制器.
The reason $http
undefined is, you are trying to get $http
dependency from link
function of directive. Basically 4th parameter of link function stands for require
controller.
理想情况下,您应该从Progressbar
构造函数中获得注入的依赖项实例.
You should Ideally get that injected dependency instance from Progressbar
constructor function.
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");
}
});
}
}
这篇关于在打字稿中创建指令以显示角度加载进度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!