Utilize AngularFire to generate a new User and invoke the factory function to showcase notifications

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

Answer №1

Utilizing solely the Firebase JavaScript library without incorporating AngularFire may limit your capabilities. AngularFire is designed on top of both the Firebase JS library and Angular, offering various benefits such as automatic synchronization of objects and arrays (which could be advantageous for managing arrays). Additionally, AngularFire manages $scope.apply effectively to ensure that view updates are seamlessly applied.

If you opt not to use AngularFire, it's essential to encapsulate the sections of your code responsible for updating the view within the $timeout service.

Explore this Plunker example

  $scope.createUser = function(){
    ref.createUser({
        email    : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3756195577541954585a">[email protected]</a>",
        password : "mypassword"
      }, function(error) {

        // Using $timeout ensures view updates
        $timeout(function() {
          if (error === null) {
            console.log("User created successfully");
            AlertService.addSuccessAlert("User created successfully");
          } else {
            console.log("Error creating user:", error);
            AlertService.addWarningAlert("Error while creating user");
          }
        });

      });
  }

I strongly recommend delving into the AngularFire documentation for a more efficient project workflow.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error message encountered in MEAN application request

Learning how to use the MEAN stack has been an exciting journey for me as I venture into building web apps. Rather than relying on yeoman generators or npm app to do the heavy lifting of generating code, I have delved into creating my entire app from scrat ...

Is there a way for me to retrieve SCSS color variables within the javascript of a Vue template?

I have a unique challenge in my application involving a component called Notification. To bring notifications to other components, I utilize the mixin method toast('message to display', 'color-variable'). My goal is to set the backgroun ...

I am still receiving an empty dropdown value despite implementing ng-selected

I am having issues with using ng-selected to retrieve the selected value from a dropdown. Instead of displaying the selected value, it appears blank. Here is the code snippet I have tried: <div> <select id="user_org" ng-model="selectedorg.all ...

Is it possible to access prop properties within the ready() function?

I am seeing the error message undefined in the console, specifically originating from the ready() function. The issue I am encountering is related to attempting to assign the value of this.users.name to this.userForm.name. Can someone please point out wh ...

Add the cordova plugin multi-image-picker with the following command

onDeviceReady: function() { window.imagePicker.getPictures( function(results) { for (var i = 0; i < results.length; i++) { alert('Image URI: ' + results[i]); } }, function ...

While running tests on a React project, the `npm test` command is successful, but unfortunately,

I created a new react app using create-react-app and included some basic components and tests. The tests work fine when running 'npm test', but I encounter an 'Unexpected token' error when using Jest to run the tests with imported compo ...

How can I collapse the dropdown menu in typeahead.js?

I am currently utilizing typeahead.js for a typeahead functionality. My goal is to achieve the opposite of what was discussed in this thread: Programmatically triggering typeahead.js result display Despite attempting to trigger a blur event on the typeah ...

Retrieving a MAC address from a device using a web script or HTTP protocol

Is it feasible, with access to all end user devices, to request the device's MAC address using web scripting in Apache/IIS/Nginx? Would PHP, Perl, or ASP be able to accomplish this task? The client devices run on iOS, so the method described here wil ...

Issue: "StoreController Undefined" error in Python Flask + Angular application

In the python flask application that I have built with Angular JS for the front end, there are three main files. app.py import json import flask import numpy as np app = flask.Flask(__name__) @app.route("/") def index(): ...

Display a div when a selection is made from the dropdown menu - using Ionic

Upon running this code, the expected behavior is to display the second div when an option is selected from the first dropdown list. Similarly, selecting an option from the second dropdown list should reveal the third div. However, the third div does not ap ...

Working with conditional rendering in React Native allows us to easily change text based on different conditions. By utilizing

Hello fellow React Native beginners! I'm currently working on a feature where the text output on the screen changes based on the time of day. Specifically, I want the screen to display 'Morning' if it's morning, 'Afternoon' i ...

Experiencing difficulty navigating JSON objects

I am facing an issue with a JSON structure that has the following format: [ { "coordinates": [ 75.71027043, 26.88661823 ] }, { "coordinates": [ 75.71027043, 26.88661823 ...

The persistence of authentication state in Next.js Firebase is inconsistent

I can't figure out why Firebase auth isn't persisting. My project is quite basic at this point, with a simple sign-in function: await signInWithEmailAndPassword(auth, email, password); In my layout.tsx, I have the onAuthStateChange: const unsubs ...

UI-Router causing issues with AngularJS anchorScroll functionality

Currently, I am utilizing ui-router and attempting to implement automatic scrolling within the controller. However, it seems that anchorScroll function is not working as expected. My assumption is that it may be due to having two '#' symbols in t ...

Exploring Protractor testing with Bootstrap modals

I'm having an issue testing a bootstrap modal. Here's the scenario: Click on a button to display the modal The modal body has a list of buttons When I click on one of them, it doesn't do anything My Protractor code snippet: element(by. ...

What is the best way to connect data so that when a user clicks on a specific card, it appears on a popup card

When a user clicks on any card containing data retrieved from a backend API GET method, that data should be displayed in a pop-up card. In my situation, I have two components: DisplayNotes.vue and UpdateNotes.vue. Whenever a user clicks on a displayed card ...

Show the JSON data returned

Looking for a way to display the JSON response in a JSP page using AJAX... function doAjaxPost() { var name = $('#name').val(); var password = $('#password').val(); var gender = $('#gender').val(); var abo ...

Vue.js: click event does not trigger transform animation

I am facing a challenge with rotating an arrow icon within a dropdown menu. Despite my efforts, the rotation does not synchronize with the appearance of the dropdown menu. Here is the Vue component code snippet: <nav> <section class= ...

Exploring the method of extracting multiple checkbox values from an HTML form

While I'm aware that jQuery can be used to retrieve checkbox values when there are multiple checkboxes, the solutions available online don't seem to work for me. This is because my checkbox inputs are embedded within an HTML form, and none of the ...

How can I pass $scope between controllers in AngularJS?

Just starting out with Angular Js. Can I pass the scope of the RestaurantController to the MenuController like this? For example: angular.module('restaurants').controller('RestaurantController', ['$scope', function($sco ...