簡體   English   中英

模型更新后,AngularJS View不會更新

[英]AngularJS View does not update after model update

我的頁面上有一個<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();
};

你需要運行一個摘要循環。

$scope.$apply()

或者

$scope.$digest() 

應該這樣做。

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

嘗試<div ng-controller="PercentageOverrideController">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM