簡體   English   中英

在 Angular-CLI 項目中使用 jQuery

[英]Using jQuery with Angular-CLI Project

我正在使用"@angular/cli": "1.0.2"angular version 4

出於某種原因,我不得不在選擇區域中使用基於 jquery 的插件,因為我在 angular 中找不到等效的插件。

這是我的組件的樣子

declare var $ : any;
//adding only necessary code
export class SelectComponent implements OnInit {

    constructor(private _ngZone: NgZone) {}

    public rowData: any = [];

    ngOnInit() {
        $('img#example').selectAreas({
            minSize: [10, 10],
            onChanged: this.debugQtyAreas,
            width: 500,
            areas: [{
                x: 10,
                y: 20,
                width: 60,
                height: 100,
            }]
        });
    }
    debugQtyAreas(event, id, areas) {
        this.rowData = areas.map(function(obj) {
            return {
                left: obj.x,
                top: obj.y,
                id: obj.id
            };
        });
    };
}

我的jquery事情是如何以這種方式工作的,我可以選擇圖像上的區域。

但是我推送/分配給數組 rowData 的值沒有在視圖中更新

我嘗試在互聯網上搜索並發現此解決方案適用於所有人但不適用於我

this._ngZone.run(() => {
      //running code inside this 
})

但我在這里遇到錯誤

無法讀取未定義的屬性“運行”

rowData 發生了同樣的事情,當我嘗試推送數據而不是從地圖中分配數據時,如下所示

for(var i = 0; i < areas.length; i++){
    this.rowData.push({
        left: areas[i].x,
        top: areas[i].y,
        id: obj.id
    });
}

它說無法讀取未定義的屬性“推送”

如果要保留this引用,則在按引用傳遞函數時需要使用bind

onChanged: this.debugQtyAreas.bind(this)

當您使用 TypeScript 編寫內聯函數時,不要使用function前綴。 如果您使用=>符號,則默認情況下this引用將持續存在。

    this.rowData = areas.map((obj) => {
        return {
            left: obj.x,
            top: obj.y,
            id: obj.id
        };
    });    

thisjQuery函數中被保留,並且不像通常那樣被引用到全局范圍。

我總是在函數的頂部添加以下幾行:

let scope = this;

然后使用scope而不是 this`,例如

scope._ngZone.run(() => {
  //running code inside this 
})

...

for(var i = 0; i < areas.length; i++){
    scope.rowData.push({
        left: areas[i].x,
        top: areas[i].y,
        id: obj.id
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM