【问题标题】:Using jQuery with Angular-CLI Project在 Angular-CLI 项目中使用 jQuery
【发布时间】:2017-07-04 13:37:41
【问题描述】:

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

由于某种原因,我不得不为 select area 使用基于 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
    });
}

它说Cannot read property 'push' of undefined

【问题讨论】:

  • 你导入NgZone了吗?
  • import { NgZone } from '@angular/core'; 这个?是的。
  • 显示完整代码。我相信我知道为什么。

标签: javascript jquery angular


【解决方案1】:

如果要持久化this 引用,则需要在通过引用传递函数时使用bind

onChanged: this.debugQtyAreas.bind(this)

当您使用 TypeScript 编写内联函数时,不要使用 function 前缀。如果您使用=&gt; 表示法,this 引用将默认保留。

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

【讨论】:

  • 该死的范围问题。有帮助。谢谢。
  • 你能告诉我为什么我的自动重载在注入 jquery 后停止工作。在它工作之前。
  • @Rakeschand 在您从 jQuery 回调中更改某些内容后,尝试注入 ChangeDetectorRef 并调用 detectChanges()。您可能还必须从 ngZone.run 内部调用该方法。我认为你有部分解决方案。 ngZone.run 具有误导性,因为它只允许您在区域更新时运行代码。
  • 好的,谢谢。我会试试的。
【解决方案2】:

this 保留在 jQuery 函数中,并且不像通常那样引用到全局范围。

我总是在我的函数顶部添加这行:

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
    });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-13
    • 2018-01-08
    • 2017-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-03
    • 1970-01-01
    相关资源
    最近更新 更多