Angular js $解析不起作用
问题描述:
我已经使用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']);
。我不明白什么是错的。错误是
this。$ parse is undefined。 和服务被称为两次
答
这是很简单的:你的this
是不是你的class'es范围,因为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 });
});
}
此语法'['$ parse',($ parse)=> new PageModal($ parse)]'看起来很尴尬。 Angular已经迫使你进行时髦的数组注入,你创建了一个具有注入服务属性的类,并且另外你创建了2次:'($ parse)=> new PageModal($ parse)'。如果你将注入10个服务会怎么样? 40次列出相同的名称? – smnbbrv