javascripthtmlangularjsangularjs-directiveng-switch

Ng-switch embedded in custom directive not getting evaluated when value changes


I created a custom directive that's basically a reusable form. Part of the form is an error message display that uses ng-switch:

<div ng-switch="status">
  <span ng-switch-when="Error" class="text-error">Error encountered</span>
  <span ng-switch-when="Verifying" class="text-info">Verifying</span>
  <span ng-switch-when="Success" class="text-success">Success</span>
  <span ng-switch-default>&nbsp;</span>
</div>

In my directive's controller, I defined a function that performs verification with the server:

$scope.verify = function () {
   $scope.status = 'verifying';
   socket.emit('verify', $scope.data, function(result) {
     $scope.status = result;
   });
};

This function is then called by the link function on blur event of an input box.

What I am noticing is that the "Verifying" state never shows up, but the "Error"/"Success" states work fine. It seems that AngularJS is processing the ng-switch directive only after my current directive has completed processing.

Is there something I'm doing wrong? Is there a way for me to get around this behaviour so that the verifying state would show up?


Solution

  • The variable is changing before Angular has completed the $digest cycle and rendered the view. Try calling emit asynchronously via $timeout, which will allow the framework to render the current view and then update it later when your data is finished loading:

    $scope.verify = function () {
       function afterLoading(){
           socket.emit('verify', $scope.data, function(result) {
               $scope.status = result;
           });
       }
       $scope.status = 'verifying';
       $timeout(afterLoading, 0);
    };
    

    (Also remember to inject the $timeout service in your controller)