为什么我的视图模板不会与AngularJS绑定到范围变量?

时间:2014-05-11 15:03:57

标签: angularjs angularjs-scope

我的观点是:

<div class="container" ng-controller="MyController">
  <div class="row">
    <div class="col-md-8">
      <textarea class="form-control" rows="10" ng-model="myWords" ng-change="parseLanguage()"></textarea>
    </div>
    <div class="col-md-4" ng-show="sourceLanguage !== null">
      Language: {{ sourceLanguage }}
    </div>
  </div>
</div>

我的控制器是:

webApp.controller('MyController', [
  '$scope', '$rootScope', 'TranslateService', function($scope, $rootScope, CodeService) {
    $scope.init = function() {
      return $scope.sourceLanguage = null;
    };
    $scope.parseLanguage = function() {
      return TranslateService.detectLanguage($scope.myWords).then(function(response) {
        console.log($scope.sourceLanguage);
        $scope.sourceLanguage = response.data.sourceLanguage;
        return console.log($scope.sourceLanguage);
      });
    };
    return $scope.init();
  }
]);

控制台日志显示正确的数据。但在视图中,sourceLanguage永远不会更新。为什么会这样?

1 个答案:

答案 0 :(得分:1)

如果您评估的承诺不是Angular上下文的一部分,则需要使用$scope.$apply

$scope.parseLanguage = function() {
  TranslateService.detectLanguage($scope.myWords).then(function(response) {
    $scope.$apply(function() {
      $scope.sourceLanguage = response.data.sourceLanguage;    
    });        
  });
};