当模型在jQuery事件中发生改变时,Angular 2不会刷新视图
Angular 2 does not refresh view when model changed from inside of jQuery event
我正在创建一个自定义搜索面板,其中包含显示搜索结果的下拉容器。
在我的控制器中我有:
export class ProductSearchComponent implements OnInit {
public hasFocus: boolean = false;
public results: SearchResult[] = null;
...
}
<form id="searchForm" autocomplete="off">
<i class="glyphicon glyphicon-refresh loadingLiveSearch" id="spinnerClass"
[style.display]="isLoading ? '' : 'none'"></i>
<input type="search" #searchInput class="searchInput" id="globalSearchInput" (keydown)="textboxKeydown($event)" placeholder="start typing searched phrase..."
(keyup)="onChangeInputText(searchInput.value)" (change)="onChangeInputText(searchInput.value)" title="Search within VerIT Store" />
<ul class="search-result" [class.hidden]="!(results != null && results?.length > 0 && hasFocus == true)">
<template ngFor let-res [ngForOf]="results" let-i="index">
<li></li>
<li *ngIf="i < 5"> {{ hasFocus ? "1" : "0" }}
<a [routerLink]="getProductLink(res)" (click)="hideList()">
<h3 [innerHtml]="markFoundPattern(res.name)"></h3></a>
<h4>{{res.desc}}</h4>
</li>
</template>
</ul>
</form>
,因为我需要隐藏结果窗格,当有人点击页面上的任何地方,我有以下代码在控制器:
public ngOnInit(): void {
// this has to be uncommented to make things work.
//window.setInterval(() => { }, 100);
$("#globalSearchInput").focusout(() => {
this.hasFocus = false;
});
$(".search-result, #globalSearchInput").focusin(() => {
this.hasFocus = true;
});
}
你能想象我花了4个小时试图在我的代码中找到一个错误,并解释为什么视图没有重新绑定更新的hasFocus
值吗?
当我开始尝试在windows中运行计数器时。setInterval来确保我还没有失去理智,然后,其他东西开始工作了
在and中,我不得不离开并清空window.setInterval(() => { }, 100)
,以确保当jQuery在事件回调中改变值时,视图也会得到更新。
但这对我来说是一种欺骗。
你能给我一个合适的方法来通知angular更新视图吗?
我已经阅读http://blog.thoughtram.io/angular/2016/02/22/angular-2-change-detection-explained.html,我试图使用ChangeDetectorRef这样:
constructor(
@Inject(ChangeDetectorRef) private ref: ChangeDetectorRef
) { }
public ngOnInit(): void {
//window.setInterval(() => { }, 100);
$("#globalSearchInput").focusout(() => {
this.hasFocus = false;
this.ref.markForCheck();
});
$(".search-result, #globalSearchInput").focusin(() => {
this.hasFocus = true;
this.ref.markForCheck();
});
}
…但是,是的,它也没有工作。
的想法,好吗?:)
我试着看看是什么问题,但无法找出为什么它不与 JQuery
工作。
但是,如果您想以 Angular2
的方式完成,您可以使用 (focus)
和 (blur)
与 input control
无需Jquery
<input type="search" #searchInput (focus)="focusIn()" (blur)="focusOut()" ...>
focusIn(){
this.hasFocus = false;
}
focusOut(){
this.hasFocus = true;
}
相关文章:
- $routeParams在传递到新视图时未定义&控制器
- Angular JS-视图不工作
- 如何在渲染新视图之前关闭所有事件
- 从Backbone中的另一个视图调用新视图
- Angular2 在创建 ngSwitch 新视图后调用自定义函数
- 使用逻辑渲染Angular局部视图
- 从 Angular.js 视图中修改方法中的数据的最佳做法
- 为什么我的对象没有在 Angular 的视图中更新
- 主干新视图反映旧模型数据
- Yeoman Angular:一个视图上的多个控制器
- 创建新视图时调用呈现函数
- 离子替换新视图的选项卡和页脚
- Angular.js-视图不't在resize事件中更改作用域变量时更新
- YII:如何将参数列表从js传递到控制器,并通过传递另一个列表来调用新视图
- AngularJS-关闭tile并从ngRepeat指令AngularJS中的模型加载新视图
- 加载Angular路由/视图后加载jQuery脚本
- 如何从Angular获得视图渲染时的回调
- 如何使用angular.js视图刷新页面
- Angular UI Router新视图,相同的URL
- Md-dialog弹出框(angular-material)作为一个新视图(约曼)加载进来