【问题标题】:How to call $scope.$apply() using "controller as" syntax如何使用“controller as”语法调用 $scope.$apply()
【发布时间】: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();
});

它是(数组wordListnotUsedWordList) 在我看来没有更新:

<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() 函数的位置,所以也许我们仔细看看控制器代码?
  • 如果您的代码不起作用,您应该将其作为另一个问题发布,因为您已经在这里询问了其他问题。否则人们会感到困惑:)

标签: angularjs angularjs-scope


【解决方案1】:

要回答这里的问题,您可以在使用 controller-as 语法时在控制器中使用 $scope() 方法,只要将 $scope 作为参数传递给函数即可。但是,使用 controller-as 语法的主要好处之一是不使用 $scope,这会造成一个难题。

正如 cmets 中所讨论的,发帖人将提出一个新问题,首先审查需要 $scope 的特定代码,并在可能的情况下提出一些重组建议。

【讨论】:

    猜你喜欢
    • 2014-10-13
    • 1970-01-01
    • 2017-12-25
    • 2015-01-26
    • 2016-02-19
    • 2018-03-04
    • 1970-01-01
    • 2013-02-13
    • 2017-04-18
    相关资源
    最近更新 更多