I'm learning how to use angulars $interval
by building a simple app that generates random string every second (inside a service) and returns it to the controller. However, I cant get the data. I am able to console.log it inside the function call, but not in the calling function inside the controller. What am I missing? I read here, but still dont get the point.
The controller:
angular.module("app").controller("authorC", function ($scope, WebService) {
$scope.generate = function () {
console.log("generating..");
WebService.generateRandom().then(function (y) {
console.log(y);
});
};
$scope.stop = function () {
WebService.stopGen();
};
});
The service:
angular.module("app").service("WebService", function ($http, $interval) {
function makeid() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 5; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
var genInterval;
this.generateRandom = function () {
genInterval = $interval(function () {
return makeid();
}, 1000);
return genInterval;
};
this.stopGen = function () {
$interval.cancel(genInterval);
console.log("Stopped");
}
});