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

时间:2016-02-08 16:58:19

标签: javascript angularjs

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

但警告未显示在页面上。

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

3 个答案:

答案 0 :(得分:0)

您可以使用$scope.apply()

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

答案 1 :(得分:0)

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

$scope.$apply()

或者

$scope.$digest() 

应该这样做。

答案 2 :(得分:0)

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

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

相关问题