angularjs – Angular指令使用Typescript接收对象作为属性
发布时间:2020-12-17 07:23:11 所属栏目:安全 来源:网络整理
导读:我正在使用Angular 1.5.8和Typescript进行开发 我有一个指令,在另一个指令(当然是另一个控制器)的范围内使用.假设Directive1,Controller1和Directive2,Controller2. 鉴于Controller1已经拥有用户信息,我想通过Directive2将此用户信息传递给Controller2,以防
我正在使用Angular 1.5.8和Typescript进行开发
我有一个指令,在另一个指令(当然是另一个控制器)的范围内使用.假设Directive1,Controller1和Directive2,Controller2. 鉴于Controller1已经拥有用户信息,我想通过Directive2将此用户信息传递给Controller2,以防止再次从后端获取信息. 我不确定这是否可以做到,但如果是这样的话会很好:) 以下是帮助我解释的代码: Directive1 HTML: <div> ... <directive2 user="{{ctrl.loggedUser}}"></directive2> ... </div> loggedUser通过对后端的调用加载到Controller1构造函数中. Directive2和Directive2Ctrl Typescript代码: class Directive2 implements ng.IDirective { controller = "Directive2Ctrl"; controllerAs = "d2Ctrl"; bindToController = { user: "@" }; restrict = "E"; templateUrl = "directive2.html"; static factory(): ng.IDirectiveFactory { const directive = () => new Directive2(); return directive; } } angular .module("app") .controller("Directive2Ctrl",Directive2Ctrl) .directive("directive2",Directive2.factory()); class Directive2Ctrl implements IDirective2Ctrl { public user: User; constructor(user: User) { // user is undefined } $onInit(user: User): void { // user is undefined } } 我找不到将用户对象传递给Directive2Ctrl的方法(甚至不确定是否可行).
使用“scope”属性而不是“bindToController”属性,并将“@”替换为“=”.
然后我使用我的特定范围的接口来获得自动完成. export interface IMyDirectiveScope extends ng.IScope { user: any; } export class Myirective { public restrict: string = 'E'; public templateUrl = "/mytemplate.html"; public link: (scope: IMyDirectiveScope,element: ng.IAugmentedJQuery,attrs: ng.IAttributes,ngModel: ng.INgModelController) => void; public scope = { user: "=" }; constructor() { var context = this; context.link = (scope: IMyDirectiveScope,ngModel: ng.INgModelController) => { //INSERT YOUR CODE //console.log(scope.user); }; } public static Factory() { var directive = () => { return new MyDirective(); }; return directive; } } 在你的HTML中,删除你的花括号. <div> ... <directive2 user="ctrl.loggedUser"></directive2> ... </div> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |