在typescript中创建指令以在angular中显示加载进度

时间:2016-07-06 14:27:51

标签: javascript angularjs angularjs-directive typescript progress-bar

我正在尝试在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请求。

2 个答案:

答案 0 :(得分:1)

$http未定义的原因是,您试图从$http指令函数获得link依赖。基本上,链接函数的第4个参数代表require控制器。

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

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");
            }
        });
    }
}

答案 1 :(得分:0)

在directiveController中定义$ scope.isLoading并从服务层进行$ http调用。

basic controller.ts

export class sampleController {

    // inject service here  
    constructor() {

    }

    public isLoading() {
        callServiceFunction();
    }
}

sampleController.$inject['service'];

在自定义指令中导入此控制器。

SampleService.ts

export class sampleService {
  constructor() {


  }

}
sampleService.$inject = ['$http'];

在app模块中注册此服务。

有关详细信息,请参阅sample Importing and exporting example large scale app architecture