【问题标题】:Angularjs view doesn't updateAngularjs视图不更新
【发布时间】:2013-10-23 00:38:09
【问题描述】:

我正在尝试通过从服务获取数据的控制器来更新视图。出于某种原因,当服务的数据更改时,视图不会更新。我从我的应用程序here 中提炼了一个示例。我尝试了各种绑定($scope.time = TimerService.value,包装在一个函数中,使用$watch - 没有成功)。

注意,在我的原始应用程序中,这是一个对象数组,并且对象的属性发生了变化。

-- script.js--

var mod = angular.module('mymodule', []);

mod.service('TimerService', function() {
  this.value = 0;
  var self = this;
  setInterval(function() {
    self.value += 1;
  }, 2000)
});

mod.controller('TimerCtrl', ['TimerService', '$scope', function(TimerService, $scope) {
  $scope.time = TimerService.value;
  $scope.$watch(function() {
    return TimerService.value;
  }, function(newValue) {
    $scope.time = newValue;  
  }, true);
  $scope.otherValue = '12345';
}]);


angular.element(document).ready(function() {
  alert('start');
  angular.bootstrap(document, ['mymodule']);
});

-- 索引.html--

<!DOCTYPE html>
<html>

  <head>
    <script src="./angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
      <div ng-controller="TimerCtrl">
          <h1>- {{ time }}-</h1>
          <h2>{{ otherValue }}</h2>
      </div>
  </body>

</html>

【问题讨论】:

    标签: javascript angularjs view angularjs-scope


    【解决方案1】:

    经过一段时间的反复试验,我终于找到了问题的答案。在我上面的示例(以及我的实际应用程序)中,数据在角度范围之外发生了变化(控制器按钮单击、http 请求等),这意味着摘要周期没有开始。如果我将代码更改为使用$timeout(),它就可以工作。不幸的是,这并不能完全解决我在角度之外更改数据的问题(我想我也需要将其余部分整合到角度中)。

    更新

    我设法通过在我的服务中使用rootscope 来执行角度之外的更改:

    $rootscope.$apply(function() {
      // perform variable update here.
      self.value += 1;
    });
    

    这成功传播到视图。

    【讨论】:

    • 当我这样做时,我得到一个“$digest 已经在进行中”的错误。你遇到过同样的问题吗?
    • 不,我没有。但是,如果您这样做,请将您的电话转入if(!$rootscope.$$phase)。这应该会有所帮助。
    • 使用 $evalAsync 代替 $apply
    【解决方案2】:

    试试这个

    $scope.time = TimerService.value;
    if(!$scope.$$phase) {
        $scope.$apply();
    }
    

    【讨论】:

    • 不,不起作用。我认为问题在于没有检测到更改。
    【解决方案3】:

    试试

    var app = angular.module('myApp', []);
                var value = 0;
                var timer = setInterval('Repeater()', 1000);
                var Repeater = function () {
                    value++;
                    var scope = angular.element(document.getElementById('myApp')).scope();
                    console.log(scope);
                    scope.$apply(function () {
                            scope.time = value;
                        });
                    };
                app.controller('TimerCtrl', ['$scope', function( $scope) {
    
              }]);
    

    感谢https://stackoverflow.com/a/16520050/356380

    【讨论】:

    • 2-way binding 不是 Angular 的优点吗?为什么我需要处理服务中的 DOM 元素?另外,该服务可能会在应用程序中的任何地方使用,所以我不知道 DOM 的哪个部分受到影响。
    猜你喜欢
    • 2016-12-05
    • 1970-01-01
    • 1970-01-01
    • 2015-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-13
    相关资源
    最近更新 更多