Решив пару ошибок благодаря @sehaxx в Значение привязки Angularjs из службы Я хотел бы представить асинхронность в примере, как в следующем коде, где переменная инициализируется асинхронно и ее значение не отражаетсяв представлении.
(function(angular) {
'use strict';
angular.
module('myServiceModule', []).
controller('MyController', ['$scope', 'notify','$log', function($scope, notify, $log) {
this.clickCount = 0;
this.clickLimit = notify.clickLimit();
this.callNotify = function(msg) {
notify.push(msg);
this.clickCount = notify.clickCount();
$log.debug("[controller] Click count is now", this.clickCount, " and limit is ", this.clickLimit);
};
}]).
factory('notify', ['$window','$log', '$timeout', function(win,$log, $timeout) {
var msgs = [];
var clickCounter = 0;
var countLimit = 0;
$timeout( function(){
countLimit = Math.floor(Math.random() * 10)+1;
$log.debug("[service] Click limit initialized at", countLimit);
return countLimit;
}, 10);
return {
clickLimit: function(){
return countLimit;
},
clickCount: function() {
clickCounter = msgs.length;
$log.debug("[service] You are clicking, click count is now", clickCounter, " limit is ", countLimit);
return clickCounter;
},
push: function(msg) {
msgs.push(msg);
clickCounter = msgs.length;
$log.debug("[service] Counter is", clickCounter, " on ", countLimit);
if (msgs.length === countLimit) {
win.alert(msgs.join('\n'));
msgs = [];
}
}
}
}]);
})(window.angular);
Рабочий пример в ручка