因此,在看了一些typescript中的angularjs指令示例之后,似乎大多数人都同意在实现它们时使用函数而不是类。
我更喜欢将它们作为一个类,并尝试按如下方式实现它们:
module directives
{
export class search implements ng.IDirective
{
public restrict: string;
public templateUrl: string;
constructor()
{
this.restrict = 'AE';
this.templateUrl = 'directives/search.html';
}
public link($scope: ng.IScope, element: JQuery, attributes: ng.IAttributes)
{
element.text("Hello world");
}
}
}
现在,这个方法工作得很好。但是,我需要一个具有某些属性的独立作用域,并且我正在努力找出如何在类本身中包含它。
逻辑规定,因为我可以
public restrict: string;
public templateUrl: string;
我应该能够拥有这样的东西:
public scope;
但我不确定这是否正确,或者如何从那里继续(即如何将属性添加到作用域中)。
有人知道怎么解决这个问题吗?(如果可能的话,希望不必恢复到函数)
谢谢,
发布于 2014-05-08 16:57:28
假设您拥有的东西在没有孤岛作用域的情况下工作,则以下内容应该与孤岛作用域一起工作:
module directives
{
export class search implements ng.IDirective
{
public restrict = 'AE';
public templateUrl = 'directives/search.html';
public scope = {
foo:'=',
bar:'@',
bas:'&'
};
public link($scope: ng.IScope, element: JQuery, attributes: ng.IAttributes)
{
element.text("Hello world");
}
}
}
发布于 2015-08-21 22:54:12
以下是我的建议:
指令:
import {directive} from '../../decorators/directive';
@directive('$location', '$rootScope')
export class StoryBoxDirective implements ng.IDirective {
public templateUrl:string = 'src/module/story/view/story-box.html';
public restrict:string = 'EA';
public scope:Object = {
story: '='
};
public link:Function = (scope:ng.IScope, element:ng.IAugmentedJQuery, attrs:ng.IAttributes):void => {
// console.info(scope, element, attrs, this.$location);
scope.$watch('test', () => {
return null;
});
};
constructor(private $location:ng.ILocationService, private $rootScope:ng.IScope) {
// console.log('Dependency injection', $location, $rootScope);
}
}
模块(registers指令...):
import {App} from '../../App';
import {StoryBoxDirective} from './../story/StoryBoxDirective';
import {StoryService} from './../story/StoryService';
const module:ng.IModule = App.module('app.story', []);
module.service('storyService', StoryService);
module.directive('storyBox', <any>StoryBoxDirective);
装饰器(添加inject和produce指令对象):
export function directive(...values:string[]):any {
return (target:Function) => {
const directive:Function = (...args:any[]):Object => {
return ((classConstructor:Function, args:any[], ctor:any):Object => {
ctor.prototype = classConstructor.prototype;
const child:Object = new ctor;
const result:Object = classConstructor.apply(child, args);
return typeof result === 'object' ? result : child;
})(target, args, () => {
return null;
});
};
directive.$inject = values;
return directive;
};
}
我考虑过将module.directive(...)
、module.service(...)
转移到StoryBoxDirective.ts
等类文件中,但还没有做出决定和重构;)
你可以在这里查看完整的工作示例:https://github.com/b091/ts-skeleton
指令在这里:https://github.com/b091/ts-skeleton/blob/master/src/module/story/StoryBoxDirective.ts
https://stackoverflow.com/questions/23535994
复制相似问题