.factory('myClass', ['$timeout',function($timeout) {
var myClass = function() {};
myClass.prototype.surprise = function() {// Do something suprising! :D};
myClass.prototype.beAmazing = function() {// Here 'this' referes to the current instance of myClass
$timeout(angular.bind(this, function() {// Run my code safely here and this is not undefined but// the same as outside of this anonymous functionthis.surprise();}));}
return new myClass();
}])
window.gapi.client.load('oauth2', 'v2', function() {var request = window.gapi.client.oauth2.userinfo.get();request.execute(function(response) {// This happens outside of angular land, so wrap it in a timeout// with an implied apply and blammo, we're in action.$timeout(function() {if(typeof(response['error']) !== 'undefined'){// If the google api sent us an error, reject the promise.deferred.reject(response);}else{// Resolve the promise with the whole response if ok.deferred.resolve(response);}});});});
//use by itself$scope.$safeApply();
//tell it which scope to update$scope.$safeApply($scope);$scope.$safeApply($anotherScope);
//pass in an update function that gets called when the digest is going on...$scope.$safeApply(function() {
});
//pass in both a scope and a function$scope.$safeApply($anotherScope,function() {
});
//call it on the rootScope$rootScope.$safeApply();$rootScope.$safeApply($rootScope);$rootScope.$safeApply($scope);$rootScope.$safeApply($scope, fn);$rootScope.$safeApply(fn);
$scope.$on('customEventName', function (optionalCustomEventArguments) {//TODO: Respond to event});
$scope.$broadcast('customEventName', optionalCustomEventArguments);
... your controller code...
$http.get('some/url', function(data){$scope.$apply(function(){$scope.mydate = data.mydata;});});
... more of your controller code...
这样做:
... your controller code...
$http.get('some/url', function(data){$timeout(function(){$scope.mydate = data.mydata;});});
... more of your controller code...
function editModel() {$scope.someVar = someVal;/* Do not apply your scope here since we don't know if thatfunction is called synchronously from Angular or from anasynchronous code */}
// Processed by Angular, for instance called by a ng-click directive$scope.applyModelSynchronously = function() {// No need to digesteditModel();}
// Any kind of asynchronous code, for instance a server requestcallServer(function() {/* That code is not watched nor digested by Angular, thus wecan safely $apply it */$scope.$apply(editModel);});