user1684161 February 2016

AngularJS View does not update after model update

I have a <div> on my page for alert message:

<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>

In my Angular controller I have a variable $scope.alerts = [ ] and function which pushes a new alert message to an array:

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

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

After I make a request and get a response, I check in debug mode that the function was invoked and that a new value was added to the array. However it does not appear on my page.

I have a test button in my div:

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

If I press this button, the alert appears on the page. If I try to invoke the same function:

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

within the code:

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

but the alert does not appear on page.

I assume that I should trigger somehow the view to show that update on page. What do you think guys? Thank you!

Answers


tyler February 2016

You can use $scope.apply()

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


rotato poti February 2016

you need to run a digest loop.

$scope.$apply()

or alternatively

$scope.$digest() 

should do it.


varun February 2016

Instead of <div ng-controller="PercentageOverrideController as ctrl">

try <div ng-controller="PercentageOverrideController">

Post Status

Asked in February 2016
Viewed 2,263 times
Voted 12
Answered 3 times

Search




Leave an answer