Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

angularjs - How to call $scope.$apply() using "controller as" syntax

I am trying to limit my use of $scope in my controllers as much as possible and replace it with the Controller as syntax.

My current problem is that i'm not sure how to call $scope.$apply() in my controller without using $scope.

Edit: I am using TypeScript 1.4 in conjunction with angular

I have this function

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 : [];
  });
}

being called from

$scope.$on("video-switch",() => {
           this.setWordLists();
});

And it's (the arrays wordList and notUsedWordList) is not being updated in my view:

<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>

Along the same lines of $apply, is there another way of calling $scope.$on using Controller as?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To answer the question at hand here, you can use $scope() methods in a controller when using the controller-as syntax, as long as you pass $scope as a parameter to the function. However, one of the main benefits of using the controller-as syntax is not using $scope, which creates a quandary.

As was discussed in the comments, a new question will be formulated by the poster to review the specific code requiring $scope in the first place, with some recommendations for re-structuring if possible.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...