Skip to content

Instantly share code, notes, and snippets.

@john24318
Last active August 29, 2015 14:03
Show Gist options
  • Save john24318/fa2edd970c7eb06021a9 to your computer and use it in GitHub Desktop.
Save john24318/fa2edd970c7eb06021a9 to your computer and use it in GitHub Desktop.
Force update scope in callback
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.18/angular.min.js"></script>
</head>
<body>
<div ng-controller="MyController">
<button id="load">Load products</button>
<my-tag></my-tag>
</div>
<script>
angular.module("myApp", [])
.factory("myProducts", function(){
var products = [];
return products;
})
.controller("MyController", ["$scope", "myProducts", function($scope, myProducts){
$scope.products = myProducts;
$("#load").on("click", function(){
setTimeout(function(){
//$scope.$apply(function(){ // Remember to add this line, callback need $apply() to force update scope
myProducts.length = 0;
for(var i=0; i<10; i++) {
myProducts.push("product "+i);
}
//});
}, 1000);
});
}])
.directive("myTag", function(){
return {
restrict: 'AE',
template: '\
<ul>\
<li ng-repeat="product in products">{{ product }}</li>\
</ul>'
}
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment