demo = angular.module('demo', [], '');
demo.controller('DemoCtrl',
function ($scope, DemoService) {
$scope.$on('asyncResult', function (event, data) {
$scope.foo = data;
});
$scope.makeAsyncCall = function() {
DemoService.makeAsyncCall($scope);
};
});
demo.factory('DemoService', function ($http, $rootScope) {
var service = {
makeAsyncCall: function (theScope) {
console.log('making a call...');
$http.get('/echo/json/?a=b&c=d').
success(function (data, status, headers, config) {
theScope.$broadcast('asyncResult', 'it worked!');
}).error(function (data, status, headers, config) {
theScope.$broadcast('asyncResult', 'it failed');
});
console.log('done');
}
};
return service;
});
<div ng-app='demo' ng-controller='DemoCtrl'>
<input type="button" ng-click="makeAsyncCall()" value="DoJSON" /><br/>
Result : {{foo}}</div>
External resources loaded into this fiddle: