2017-06-20 81 views
0

我想将我的表与它们的过滤器和排序功能外包为指令。 因为我想用双向-数据绑定我这样做:如何使用AngularJS和TypeScript在控制器和指令之间使用双向数据绑定

public bindToController = { 
     cars: "=" 
}; 

这是因为汽车上的点击表格中的时候,我改变这辆车的属性,我需要的控制器,其中cars来源于此。

export class CarsTableDirectiveController implements ng.IComponentController { 
    public cars; 


    public $onInit() { 
     console.log(this.cars); 
    } 
    constructor() { 
     console.log(this.cars); 
    } 

} 


export class CarsTable implements ng.IDirective { 

    public restrict: string = "E"; 
    public scope = {}; 
    public controller = CarsTableDirectiveController; 
    public controllerAs: string = '$ctrl'; 
    public bindToController = { 
     cars: "=" 
    }; 

    static instance(): ng.IDirective { 
     return new CarsTable(); 
    } 

    template: string = require<string>('./cars-table.html'); 

} 

我打电话这样说:

<projects-table cars="ctrl.cars"></projects-table> 

的汽车数据表中显示,但是当我登录cars它总是不确定的。 我在做什么错?如何实现对象cars的双向数据绑定并使用CarsTableDirectiveController中的变量cars

+0

你能告诉我你是如何使用这个指令吗? –

+0

对不起,刚添加它。 – testiguy

+0

汽车是否立即可用?或者他们来自AJAX电话? –

回答

1

你的代码看起来不错,这让我觉得汽车不是马上可用(它们是否来自AJAX调用?)。因此当constructor$onInit火灾时,汽车还没有。

您可以使用ng-if等到汽车存在创建指令:

<projects-table ng-if="cars.length" cars="cars"></projects-table> 

现在你应该看到汽车时$onInit火灾(但不一定当constructor火灾)。

+0

非常感谢!这是问题所在。 – testiguy

相关问题