I recently started working with AngularJS and wanted to integrate it with AngularFire/Firebase for storing project data. I created a factory that manages notifications to be displayed in a centralized location. Here is the structure of my factory:
myApp.factory("AlertService", function($timeout){
var alerts = new Array();
var addAlert = function(type, message){
alerts.push({
type: type,
msg: message
});
$timeout(function(){
removeAlert(alerts.length - 1);
}, 3000);
}
var removeAlert = function(index){
alerts.splice(index, 1);
}
return{
alerts : alerts,
addSuccessAlert : function(message){
addAlert("success", message);
},
addDangerAlert : function(message){
addAlert("danger", message);
},
deleteAlert : function(index){
removeAlert(index);
}
};
});
In the controller, I bound the data using $watch
$scope.$watch( function () { return AlertService.alerts; }, function ( alerts ) {
$scope.alerts = AlertService.alerts;
});
Then, I added a div in the index.html file:
<div id="alert">
<alert ng-repeat="alert in alerts" type="{{alert.type}}">{{alert.msg}}</alert>
</div>
Everything was functioning correctly when I called
AlertService.addWarningAlert("Your password is not identical");
from a controller. However, when I attempted to display a notification after creating a user in Firebase, the data binding did not update (only the array). This is how I create a user:
var ref = new Firebase("https://xyz.firebaseio.com/");
ref.createUser({
email : $scope.data.suEmail,
password : $scope.data.suPassword
}, function(error) {
if (error === null) {
console.log("User created successfully");
AlertService.addSuccessAlert("User created successfully");
} else {
console.log("Error creating user:", error);
AlertService.addWarningAlert("Error creating user");
}
});
Any suggestions on what mistake I might be making? Thank you in advance!
Edit: Here is the Plnkr link for reference http://plnkr.co/edit/jSaJ5EzZ5MGRPFzhbGJg?p=preview