Skip to content

Instantly share code, notes, and snippets.

@bennadel
Created April 9, 2014 11:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bennadel/10258858 to your computer and use it in GitHub Desktop.
Save bennadel/10258858 to your computer and use it in GitHub Desktop.
$scope.$evalAsync() vs. $timeout() In AngularJS
<!doctype html>
<html ng-app="Demo">
<head>
<meta charset="utf-8" />
<title>
$scope.$evalAsync() vs. $timeout() In AngularJS
</title>
</head>
<body>
<h1>
$scope.$evalAsync() vs. $timeout() In AngularJS
</h1>
<p bn-timing>
Check the console!
</p>
<!-- Load scripts. -->
<script type="text/javascript" src="../../vendor/jquery/jquery-2.0.3.min.js"></script>
<script type="text/javascript" src="../../vendor/angularjs/angular-1.2.4.min.js"></script>
<script type="text/javascript">
// Create an application module for our demo.
var app = angular.module( "Demo", [] );
// -------------------------------------------------- //
// -------------------------------------------------- //
// Test the timing of the $timeout() and $evalAsync() functions.
app.directive(
"bnTiming",
function( $timeout ) {
// I bind the JavaScript events to the local scope.
function link( $scope, element, attributes ) {
$timeout(
function() {
console.log( "$timeout 1" );
}
);
$scope.$evalAsync(
function( $scope ) {
console.log( "$evalAsync" );
}
);
$timeout(
function() {
console.log( "$timeout 2" );
}
);
}
// Return the directive configuration.
return({
link: link
});
}
);
</script>
</body>
</html>
// PSEUDO-CODE for AngularJS directive link function.
function link( $scope ) {
function handler( data ) {
$scope.$apply(
function() {
// ...
}
);
}
if ( cachedData ) {
handler( cachedData );
} else {
getDataAsync( handler );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment