【问题标题】:AngularJS View does not update after model update模型更新后AngularJS视图不更新
【发布时间】:2016-02-08 16:58:19
【问题描述】:

我的页面上有一个<div> 用于提醒消息:

<div ng-controller="PercentageOverrideController as ctrl">
  <script type="text/ng-template" id="alert.html">
    <div class="alert" style="background-color:#fa39c3;color:white" role="alert">
      <div ng-transclude></div>
    </div>
  </script>
  <uib-alert ng-repeat="alert in alerts" type="{{alert.type}}" close="closeAlert($index)">{{alert.msg}}</uib-alert>
  <button type="button" class='btn btn-default' ng-click="addAlert()">Add Alert</button>
</div>

在我的 Angular 控制器中,我有一个变量 $scope.alerts = [ ] 和将新警报消息推送到数组的函数:

$scope.showSuccess = function(){
  $scope.alerts.push({type: 'success', msg: 'Threshold Overrided'});
};

$scope.showError = function(){
  $scope.alerts.push({type: 'danger', msg: 'Error has been happened'});
};

在我发出请求并得到响应后,我在调试模式下检查该函数已被调用,并且新值已添加到数组中。但是它没有出现在我的页面上。

我的div 中有一个测试按钮:

<button type="button" class='btn btn-default' ng-click="addAlert()">Add Alert</button>

如果我按下此按钮,页面上会出现警报。如果我尝试调用相同的函数:

$scope.addAlert = function() {
  $scope.alerts.push({msg: 'Another alert!'});
};

在代码中:

$scope.showSuccess = function(){
  $scope.alerts.push({type: 'success', msg: 'Threshold Overrided'});
  $scope.addAlert();
};

但警告没有出现在页面上。

我假设我应该以某种方式触发视图以在页面上显示该更新。你们觉得怎么样? 谢谢!

【问题讨论】:

  • 尝试更简单...在您的 HTML 中添加一个简单的 {{alerts}} 并查看是否有任何变化。
  • 你能发一个 JSFiddle 吗?
  • 当我使用 {{alerts}} 时,它只显示通过按钮添加的对象。唔。需要检查一下。谢谢!
  • 那是因为 alerts 是一个数组。
  • 如何调用$scope.showError$scope.showSuccess?正如答案所暗示的那样,模型很可能在 Angular 摘要周期之外被修改,这将导致此类问题。

标签: javascript angularjs


【解决方案1】:

您可以使用$scope.apply()

$scope.showSuccess = function(){
  $scope.alerts.push({type: 'success', msg: 'Threshold Overrided'});
  $scope.addAlert();
  $scope.apply();
};

【讨论】:

    【解决方案2】:

    而不是&lt;div ng-controller="PercentageOverrideController as ctrl"&gt;

    试试&lt;div ng-controller="PercentageOverrideController"&gt;

    【讨论】:

      【解决方案3】:

      你需要运行一个摘要循环。

      $scope.$apply()
      

      或者

      $scope.$digest() 
      

      应该这样做。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-02-13
        • 2013-12-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-31
        • 1970-01-01
        相关资源
        最近更新 更多