Last active
August 29, 2015 14:03
-
-
Save john24318/fa2edd970c7eb06021a9 to your computer and use it in GitHub Desktop.
Force update scope in callback
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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