AngularJS ng-cloak does not prevent code blinking in Mean.js

This applies to the MEAN.js. I have if-statements in my Angular view to check if I have any results from my database. If there are results, I show them, if not, then I will show an error message.

I have a problem with Angular blinking: when the page loads, for a second or seconds I see an error message and then immediately displays the results from my database. The ng-cloak directive does not work.

Code

Below I have included very simple Angular code that should clearly indicate what I am doing.

Controller:

 // Return a specific person from the database. this.person = Persons.get({ personId: $stateParams.personId }); 

View:

 <div ng-if="personCtrl.person.length"> <!-- Show person details here... --> </div> <div ng-if="!personCtrl.person.length" ng-cloak> <p>Sorry, person could not be found.</p> </div> 

I tried adding the ng-cloak directive, which does not work. MEAN.js also uses Bootstrap and provides several CSS classes, but no matter which one I add, none of them work:

 [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak { display: none !important; } 

In short: I can add the ng-cloak directive and the ng-cloak CSS class, but they do not work. I can add style="display:none;" but this hides the error message even if it should be displayed.

+6
source share
2 answers

Perhaps this is what you are looking for?

 <div ng-show="personCtrl.person.length"> <!-- Show person details here... --> </div> <div ng-hide="personCtrl.person.length" ng-cloak> <p>Sorry, person could not be found.</p> </div> 
+3
source

Your problem is not with ng-cloak, it is delayed from the server.

The solutions are intended for state management either using jQuery inside the directive (recommended) or inside the controller.

Here I examined the principle in a very crude form http://plnkr.co/edit/sSVHl5AXkltjvBrpKR4s

 app.controller('HomePage', function($scope, $timeout){ $scope.user = false; var el = angular.element('#user-data-loading-zone'); // modelling 1000ms latency from the server $timeout(function(){ $scope.user = {name: 'John'}; if($scope.user) { el.removeClass('loading'); el.addClass('success'); el.html('Success data was loaded => ' + $scope.user.name); } else { $scope.state = 'Error unable to load'; } }, 1000); }); 

Usually states ...

  • Loading...
  • Success! or Error!

Use jquery and css to smooth the animation experience. Use directives to find out the above code and make it reusable.

0
source

Source: https://habr.com/ru/post/986182/


All Articles