javascriptangularjsonsen-uimonaca

OnsenUI, Angular and refreshing a UI component after an alert dialog


I am working on a mobile app using Monaca, OnsenUI and Angular. In a page, I have a list of tappable items; when a user taps an entry, a dialog should appear to enter a value. That value should be displayed in the tapped list item. It does work, kinda, but the value is not refreshed until I tap the list item again, even if only to cancel the dialog. I would like the displayed value to be updated immediately after the user closes the dialog.

Here is an HTML snippet:

<ons-page>

  <ons-row style="margin-top: 10px; text-align: center;">
    <ons-col ng-controller="NewSubmissionController">
      <ons-list id="materialList" style="margin-top: 12px;">
        <ons-list-header>Pick the Materials</ons-list-header>
        <ons-list-item modifier="tappable" ng-click="doPickMaterial('ferrous')">
          Ferrous (<span ng-bind="materialCounters['ferrous']"></span>)
        </ons-list-item>
        <ons-list-item modifier="tappable" ng-click="doPickMaterial('non-ferrous')">
          Metal, non-ferrous ({{materialCounters['non-ferrous']}})
        </ons-list-item>
        <ons-list-item modifier="tappable" ng-click="doPickMaterial('plastic')">
          Plastic ({{materialCounters['plastic']}})
        </ons-list-item>
        <ons-list-item modifier="tappable" ng-click="doPickMaterial('other')">
          Other ({{materialCounters['other']}})
        </ons-list-item>
      </ons-list>
    </ons-col>
  </ons-row>

</ons-page>

Here is the controller:

app.controller('NewSubmissionController', function($scope) {

  $scope.materialCounters = {
    'ferrous': 0,
    'non-ferrous': 0,
    'plastic': 0,
    'other': 0
  };

  $scope.doPickMaterial = function(matType) {
    ons.notification.prompt({
      title: 'Material: ' + matType,
      message: 'Please enter number of items',
      cancelable: true,
      animation: 'slide',
      callback: function(newCt) {
        alert('Input value: *' + newCt + '*');
        if (newCt != null) {
          if (newCt == '') { //  An empty input will be taken as zero
            newCt = 0;
          }
          $scope.materialCounters[matType] = n;
          alert('Count for ' + matType + ': ' + $scope.materialCounters[matType]);
        }
      }
    });
  };
});

I tried both using ng-bind and the double curly brackets notation but there was no difference in behaviour.


Solution

  • Basically if you want to update the view you can just call $scope.apply() manually and everything should update itself. There is probably some "smarter" solution, but since you're using ons.notification.prompt this looks like the easiest one.