Angular js $ parse不起作用

时间:2016-04-29 05:06:12

标签: angularjs-directive typescript

我已经使用typescript编写了一个指令。这是我的指示如下。

   'use strict';

    module App.Directives {

    interface IPageModal extends ng.IDirective {
    }

    interface IPageModalScope extends ng.IScope {

    }

    class PageModal implements IPageModal {
        static directiveId: string = 'pageModal';
        restrict: string = "A";

        constructor(private $parse: ng.IParseService) {

        }

        link = (scope: IPageModalScope, element, attrs) => {

            element.click((event) => {
                event.preventDefault();

                var options = {
                    backdrop: 'static',
                    keyboard: false
                };

                event.openModal = function () {
                    $('#' + attrs['targetModal']).modal(options);
                };
                event.showModal = function () {
                    $('#' + attrs['targetModal']).modal('show');
                };
                event.closeModal = function () {
                    $('#' + attrs['targetModal']).modal('hide');
                };
                var fn = this.$parse(attrs['pageModal']);
                fn(scope, { $event: event });
            });
        }
    }

    //References angular app
    app.directive(PageModal.directiveId, ['$parse', $parse => new PageModal($parse)]);
}

在HTML中使用

<button class="btn blue-grey-900" target-modal="emplpyeeViewModal" page-modal="vm.addEmployee($event)">
    <i class="icon-plus  m-b-xs"></i>
</button>

在控制器中使用

addEmployee($event) {
    $event.openModal();
};

此行不起作用。 var fn = this.$parse(attrs['pageModal']);。我无法理解有什么不对。错误是

  

这个。$ parse未定义。   和服务被召唤两次

1 个答案:

答案 0 :(得分:0)

这非常简单:您的this不是您的班级范围,因为function openmodal(event) {定义了自己的范围。

在类级别声明函数或使用箭头函数,例如

link = (scope: IPageModalScope, element, attrs) => {
    element.click((event) => {
        event.preventDefault();

        var options = {
            backdrop: 'static',
            keyboard: false
        };

        event.openModal = function () {
            $('#' + attrs['targetModal']).modal(options);
        };
        event.showModal = function () {
            $('#' + attrs['targetModal']).modal('show');
        };
        event.closeModal = function () {
            $('#' + attrs['targetModal']).modal('hide');
        };
        var fn = this.$parse(attrs['pageModal']);//does not work here
        fn(scope, { $event: event });
    });
}