如何获得这个'在typescript angular 1.4指令中的类的上下文

时间:2015-08-01 00:26:35

标签: angularjs angularjs-directive typescript

我最近开始在我的角度指令中使用bindToController而且我的问题是'这个'。在我的控制器方法中,如何访问MultiSelect类的属性。 '这'在那个上下文中指的是由于controllerAs语法而导致的$ scope,但现在我如何访问我的searchService服务呢?

/// <reference path="../../../../definitions/app.d.ts" />
module App.directives
{
    'use strict';

    class MultiSelect implements ng.IDirective 
    {
        restrict = 'E';
        templateUrl = 'directives/multi-select/multi-select.directive.html';
        scope = {};
        bindToController = {
            value: '='
        };
        controllerAs = 'multiSelect';

        constructor(private searchService: App.ISearchService) {

        }

        controller() 
        {
            console.log(this)
            // prints {value: undefined}
            // which matches bindToController

            this.searchService.get();
            // TypeError: Cannot read property 'get' of undefined
        }

        link = ($scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) => {


        }

        static factory(): ng.IDirectiveFactory 
        {
            const directive = (searchService: App.ISearchService) => new MultiSelect(searchService);
            return directive;
        }
    }

    angular.module('App').directive('multiSelect', ['searchService', MultiSelect.factory()]);
}

2 个答案:

答案 0 :(得分:0)

  

我最近开始在我的angular指令

中使用bindToController

唐&#39;吨。这会将this的语义更改为与TypeScript推断的不同。

答案 1 :(得分:0)

根据Dan Wahlin的说法,这是怎么做的。来自Angular in 20 Typescript project.

///<reference path="../../../tools/typings/tsd.d.ts" />
///<reference path="../../../tools/typings/typescriptApp.d.ts" />

module demoApp.directives {

    class FilterTextbox implements ng.IDirective {

        static instance() : ng.IDirective {
            return new FilterTextbox();
        }

        template = 'Search: <input type="text" ng-model="vm.filter" /> {{ vm.message }}';
        restrict = 'E';
        scope = {
            filter: '='
        };
        controller: ($scope: ng.IScope) => void;
        controllerAs = 'vm';
        bindToController = true;

        constructor() {
            this.controller = function ($scope: ng.IScope) {
                var vm = this;
                vm.message = 'Hello';

                $scope.$watch('vm.filter', (newVal, oldVal) => {
                    if (oldVal !== '' && newVal === '') {
                        vm.message = 'Please enter a value';
                    } else {
                        vm.message = '';
                    }
                });
            };
        }
    }

    angular.module('demoApp').directive('filterTextbox', FilterTextbox.instance);

}