【发布时间】:2015-01-18 17:27:16
【问题描述】:
我试图在我的控制器中尽可能限制$scope 的使用,并将其替换为Controller as 语法。
我目前的问题是我不确定如何在不使用$scope 的情况下在我的控制器中调用$scope.$apply()。
编辑:我将 TypeScript 1.4 与 angular 结合使用
我有这个功能
setWordLists() {
this.fetchInProgress = true;
var campaignId = this.campaignFactory.currentId();
var videoId = this.videoFactory.currentId();
if (!campaignId || !videoId) {
return;
}
this.wordsToTrackFactory.doGetWordsToTrackModel(campaignId, videoId)
.then((response) => {
this.fetchInProgress = false;
this.wordList = (response) ? response.data.WordList : [];
this.notUsedWordList = (response) ? response.data.NotUsedWords : [];
});
}
被调用
$scope.$on("video-switch",() => {
this.setWordLists();
});
它是(数组wordList 和notUsedWordList)
在我看来没有更新:
<div class="wordListWellWrapper row" ng-repeat="words in wordTrack.wordList">
<div class="col-md-5 wordListWell form-control" ng-class="(words.IsPositive)? 'posWordWell': 'negWordWell' ">
<strong class="wordListWord">{{words.Word}}</strong>
<div class="wordListIcon">
<div class="whiteFaceIcon" ng-class="(words.IsPositive)? 'happyWhiteIcon': 'sadWhiteIcon' "></div>
</div>
</div>
<div class="col-md-2">
<span aria-hidden="true" class="glyphicon-remove glyphicon" ng-click="wordTrack.removeWord(words.Word)"></span>
</div>
</div>
与$apply 相同,是否有另一种方法可以使用Controller as 调用$scope.$on?
谢谢!
【问题讨论】:
-
对于
$apply和$on,您必须使用$scope(或$rootScope)。 -
在 99% 的情况下,只需要在 Angular 不知情的情况下直接操作 dom 时调用
$scope.$apply()。不幸的是,当某些东西不起作用时,许多人会求助于$scope.$apply()作为“修复所有”,但通常更好的做法是更正代码,以便 Angular 知道正在发生的事情。 -
@Andrew,您是否在我的代码中看到任何可以解决我的问题的损坏或编写不佳的内容?
-
您的代码并没有真正显示控制器中
$scope.$on()函数的位置,所以也许我们仔细看看控制器代码? -
如果您的代码不起作用,您应该将其作为另一个问题发布,因为您已经在这里询问了其他问题。否则人们会感到困惑:)