Obtain an instance of a factory object in AngularJS

How can I determine the instance of an object created using an AngularJS factory?

angular.module('so')
    .factory('UserFac', function () {
        return function (first, last) {
             return {
                 name : first + ' ' + last
             };
        }
    })
    .controller('UserCtrl', function (User) {
        var user = new UserFac('John', 'Doe');

        function checkUserInstance(userObj) {
            // your answer here...
        }

        if (checkUserInstance(user)) {
            // implementation doesn't matter
        }
    });

I've tried common JavaScript methods like:

user instanceof UserFac

and

typeof user === 'UserFac'

as well as

user.constructor === UserFac

and

user.prototype === UserFac

However, it seems that the internal workings of AngularJS hide the prototype/constructor property for factories/services.

Searching online has been challenging, as most results discuss the distinction between service and factory.

Any assistance would be appreciated. Thank you!

Answer №1

One issue you may encounter is that the constructor function in your code is anonymous. Another concern is that you are returning an object literal (which is not an instance of your constructor function, but rather an instance of Object constructor) from within your constructor function.

instanceof will function correctly if implemented as demonstrated below:

angular.module('so', []);
angular.module('so')
  .factory('UserFac', function() {
    function UserFac(first, last) {
     //--------^-- remember to assign it the factory name
      this.name = first + ' ' + last
     //-^-- utilize the internal object created with the use of this keyword
    }
    return UserFac;
  })
  .controller('UserCtrl', function(UserFac) {
    var user = new UserFac('John', 'Doe');
    console.log(user instanceof UserFac)
  });

Answer №2

Completely agree with @T.J. Another approach you can take is to also implement it like this.

If you are interested, you can explore their official documentation on how Angular actually handles named providers. This practice has been established as best practice by the Angular community itself.

Link to Fiddle Here

Here's the code snippet:

angular.module('so', []);
angular.module('so')
  .factory('UserFac', function UserFac() {
   return function (first, last) {
      this.name = first + ' ' + last
    }
  })
  .controller('UserCtrl', function(UserFac) {
    var user = new UserFac('John', 'Doe');
    console.log(user instanceof UserFac)
    console.log("Name:"+user.name);
  });

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 in delete operation due to CORS in Flask API

After successfully developing a rest api in Flask and testing all api endpoints with Postman, I encountered an issue while working on an application in Javascript that consumes the resources of my api. The problem lies in consuming an endpoint that uses t ...

"Leaflet automatically refreshes tile cache when zooming in or out

Currently, I'm facing an issue regarding the tile cache in leaflet. If I move from point A to point B, and examine the tiles in between, they are cached without any problems. However, if I go from A to B, zoom in and out, and then return to point A, ...

Shifting content results in Vue transitions

I've encountered an issue with transitioning content shifts. My data array is displayed in different areas of the DOM based on the state. The main idea: OPEN feedback 1 [ complete ] feedback 2 [ complete ] feedback 3 [ complete ] CLOSED Goal: ...

Updating information within an ArcGIS Service using REST and JSON using jQuery/JavaScript

I've been attempting to update information in a feature within an arcgis service using REST and JSON. I've created a function that is supposed to be called, but the output I'm receiving is not providing me with any clear direction. I am als ...

Toggle JavaScript Query Display

Welcome to my HTML test website where I am testing show/hide JavaScript functionality. Upon loading the page, you may notice that everything is hidden until a button is clicked. <html> <head><title>Test</title> <scr ...

I am encountering undefined values when utilizing momentjs within Angular

My project is utilizing angular and momentJS, with the addition of the angular-moment library. You can find my current progress in this fiddle However, I am encountering an error when trying to use moment in a controller method: TypeError: undefined is n ...

The feature to hide columns in Vue-tables-2 seems to be malfunctioning

The issue I'm facing is with the hiddenColumns option not working as expected. Even when I set it to hiddenColumns:['name'], the name column remains visible. I've updated to the latest version, but the problem persists. UPDATE I am tr ...

AngularJS is not recognizing the starting number as zero when using ng-pattern

When validating a phone number in Brazil, it must start with zero and be 8 digits long. The input field provided is: <input type="number" name="mobileNo" ng-model="booking.phone" ng-pattern="/^[0-9]{8,8}$/" required placeholder="Phone no"> The vali ...

Having trouble sending a GET request from the client to my backend route using axios in a React-Node.js/Express setup. Where did I go wrong?

Struggling with making an API request from my backend route (using nodes/express). I'm making an axios request from the client site using React. The express backend route works fine, so the issue must be in my client-side code. I've been stuck on ...

Is there a way to efficiently manage multiple modules in AngularJS? I've put in a lot of effort, but while one module is functioning properly, the

angular .module('ApplicationOne',[]) .controller('myControllerOne', function($scope){ $scope.name = "Luther"; $scope.fname = "Martin"; $scope.ed = "B.TECH"; }); angular .module('App2&apos ...

The value of the $scope variable remains constant within the function

I am facing an issue with a scope variable that I passed to a function. Even though the variable is accessible inside the function, its value does not change when I try to modify it. Below is my HTML code: <div class="console_item" ng-class="dropdwns.a ...

Struggling to retrieve the data from a RESTful API?

I'm currently learning how to fetch an API in javascript and I'm encountering some difficulties in extracting specific parts of the response body. My goal is to store the setup and punchline of a joke in variables for later use. Here is the code ...

Unable to conduct search as search button is malfunctioning

I am experiencing an issue with an input field on my results page. I have implemented the following event: onkeypress="if (event.keyCode == 13) {document.getElementById('results-search').click()}" However, when I try to perform a search, nothin ...

Tips for organizing date columns in Bootstrap-Vue when utilizing a formatter for presentation purposes

I am working with a table containing date objects, and I have transformed them for display using the following code: { key: "date", formatter: (value, key, item) => { return moment(value).format("L"); }, sortable: true } However, this ...

Navigating array usage in Selenium IDE

I am trying to extract emails from a webpage using Selenium for future testing. I need to compare these emails with ones displayed in a selection later on. I attempted to read the emails within a while-loop but struggled with handling arrays in IDE. Unfor ...

Issue with AdminLite 2.4.0 data table functionality malfunctioning

Check out this template that I'm using. I've copied all the contents for the bower_components and dist folders, and made sure to link and require everything properly. There are no 404 errors, only status code 200. Here is a snippet of my code: ...

Grab and deliver the particular tab that is currently in view

Within my background.js file, I am aiming to capture a specific area within a div. Here is a snippet of my code: function main() { chrome.tabs.query( {'active': true}, check_tab ); } function check_tab( tabs ) { for (i = 0; i < tabs. ...

Dragging the entire ForceDirected Graph in D3.js is not functioning

tag, I am currently working on implementing a D3 force directed graph using D3 v6 and React. The graph includes features such as zoom functionality and draggable nodes. However, as the graph can become quite complex and large due to dynamic data, I aim to ...

Use jQuery to change the date format from Feb 17, 2012 to 17/02/2012

Here is the code snippet I am working with: let Date = "Feb 17, 2012"; Is there a way to transform it into Date = "17/02/2012" by utilizing jQuery? ...

Filtering Data with MongoDB Queries

In my data filtering form, I have approximately 15 to 20 dropdown fields. These dropdown fields are meant to provide various options for filtering data. As shown in the image below (from the Zoopla App): https://i.sstatic.net/KOBcc.png The image displays ...