angularjs – Angular指令使用Typescript接收对象作为属性

前端之家收集整理的这篇文章主要介绍了angularjs – Angular指令使用Typescript接收对象作为属性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用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>
原文链接:https://www.f2er.com/angularjs/141816.html

猜你在找的Angularjs相关文章