AngularJS 视图在模型更新后不会更新

AngularJS View does not update after model update

本文关键字:更新 模型 视图 AngularJS      更新时间:2023-09-26

我的页面上有一个警报消息<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();
};

但警报不会显示在页面上。

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

您可以使用$scope.apply()

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

而不是<div ng-controller="PercentageOverrideController as ctrl">

试试<div ng-controller="PercentageOverrideController">

您需要

运行摘要循环。

$scope.$apply()

或者

$scope.$digest() 

应该这样做。