When you need to make a blocking call in Angular JS you may find the $q service handy. It’s built right into the base Angular framework, and will free up the browser when performing actions that can take some time. Here is a complete, but simple example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
<html ng-app="testApp"> <head><title>Q Service</title> <script src="angular.js"></script> <script> var testApp = angular.module('testApp',[]); testApp.controller('QServiceTest', function($scope, $q){ $scope.checkIfNumber = function() { var deferred = $q.defer(); var toCheck = $scope.textToCheck; setTimeout(function(){ if(customNumberChecker(toCheck)) { deferred.resolve("It's a number"); }else{ deferred.reject("It's not a number"); } },100); var promise = deferred.promise; promise.then(function(a){ // Called for resolved $scope.outputMessage = toCheck + " is a number"; },function(b){ // Called for reject $scope.outputMessage = toCheck + " is not a number"; }); }; }); var customNumberChecker = function(input) { return !isNaN(input); } </script> </head> <body> <div ng-controller="QServiceTest"> <label>Enter a number</lable> <input type="text" ng-model="textToCheck"> <input type="button" value="check" ng-click="checkIfNumber()"> {{outputMessage}} </div> </body> </html> |