Is it possible for Angular to either remove my object from the scope or combine it with my provider during execution?

I'm trying to figure out how to handle an object called xyzApi in my code. This object is defined outside of my angular code and contains classes and utility methods that I want to make accessible to the rest of my API.

This is what it looks like (in a nutshell):

var xyzApi = xyzApi || {
    entities : new function () {
        this.oAuthToken = function (token, expires, type) {
            this.token = token;
            this.expires = expires;
            this.type = type;
            this.toString = function () {
                if (this.token != null)
                    return this.type + ' ' + this.token;
                return null;
            };
        };
    }
};

Now, within my angular service layer, I've created a provider named xyzApi as well. Here's a snippet of how it's set up:

(function () {
    angular.module('xyzDataWebServices').provider('xyzApi', function () {
        var baseUrl;
        this.setBaseUrl = function (value) {
            baseUrl = value;
        };
        this.$get = ['$log', 'baseRequest', 'xyzApiContext', 'xyzApiAuthentication', 'xyzApiLibrary', function xyzApiFactory($log, baseRequest, xyzApiContext, xyzApiAuthenication, xyzApiLibrary) {
            baseRequest.setServiceUrl(baseUrl);
            var factory = {
                context: xyzApiContext,
                authentication: xyzApiAuthenication,
                library: xyzApiLibrary
            }
            return factory;
        }];
    });
})();

My question is, when using the provider in my code, will the original object automatically merge with the provider, or will being in scope of a controller using the provider hide the original object?

Answer №1

If I have grasped it correctly, you can combine your factory and xyzApi within your provider.

I believe this does not happen automatically. However, if you include angular.merge(factory, xyzApi); in your provider, it should function as desired.

angular.merge() is compatible with Angular 1.4 or later. Alternatively, angular.extend() may work but might not achieve deep merging.

Please check out the demonstration below or visit this jsfiddle link.

The demo illustrates the merging of these two objects.

var xyzApi = xyzApi || {
sayHello: function() {
  return "hey there\n";
  }
};

angular.module('demoApp', [])
.controller('MainController', MainController)
  .provider('xyzApi', function XyzApiProvider() {
  
  this.$get = function() {
  
  var xyzApiFactory = {
      otherFunction: function() {
        //$log.log('other function called');
        return 'other function \n';
      }
  };
    //console.log(xyzApiFactory, xyzApi);
    angular.merge(xyzApiFactory, xyzApi);
    return xyzApiFactory;
  };
});
  

function MainController(xyzApi) {
var vm = this;
  vm.test = '';
  
vm.sayHello = function() {
  vm.test += xyzApi.sayHello() + xyzApi.otherFunction();
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-rc.0/angular.js"></script>
<div ng-app="demoApp" ng-controller="MainController as mainCtrl">
<pre>{{mainCtrl.test}}</pre>
  <button ng-click="mainCtrl.sayHello()">
  say hello!!
  </button>
</div>

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

Troubleshooting Controller Action Failure in AJAX Request

Hello there I am encountering an issue with my AJAX call not reaching the Controller action in my ASP.NET MVC web application project. Below, you will find my AJAX call written in Javascript and the corresponding Controller's Action. Here is the AJA ...

The elusive Yeoman composeWith module remains elusive and cannot be found

Feeling stuck on a coding problem. I've created a generator that contains other generators. When I install it from my local copy using npm link, composeWith works perfectly. But when I install the generator from GitHub, I encounter an error stating " ...

Retrieve items from the parent row of selected checkboxes

Within my table, I have the following row. <tr class="data_rows" ng-repeat='d in t2'> <td class="tds"> <input class='checkBoxInput' type='checkbox' onchange='keepCount(this)'></td> &l ...

I'm having trouble getting my bot command handler to function properly

When it comes to my command handler, the commands function properly. However, when I attempt to include arguments like $user-info @user instead of just $user-info, it returns an error stating that the command is invalid. Code //handler const prefix = &ap ...

Changing the image source dynamically at runtime using JavaScript and jQuery

Is it possible to dynamically change the source of an image using jQuery during runtime? I have set up a jsfiddle to demonstrate my question. I am attempting to load the image specified in the variable $newsrc when a button is clicked. However, I am unsure ...

Converting SVG with an external PNG file embedded into a standalone PNG format using Node

Does anyone know of a node package that can convert an svg file to a png, including external images embedded within the svg code like this? <?xml version="1.0" encoding="utf-8"?> <svg viewBox="0 0 120 120" height="120" width="120" xmlns="h ...

The Google calendar is displaying an invalid JSON file

We're in the process of developing a website using AngularJS and we need to integrate Google Calendar events. I've attempted to retrieve the data from a Google Calendar. You can locate the JSON file here: http://www.google.com/calendar/feeds/[em ...

Sort array based on priority of name property in AngularJS

Is there a way to specifically filter search results based on the name before "manager"? I am unable to use track by because I am not utilizing ng repeat in reality, but rather a directive. You can view an example of my issue on this JSFiddle. For instan ...

The Material-UI Select component does not reflect changes after an onChange event

I've encountered this issue all over the internet, but no explanation seems to resolve it for me. Using Material-UI Select and traditional setState(...) in React (not using hooks). The core of my component is as follows: class MyComponent extends Co ...

Is there a way to retrieve JSON data using Vue and Axios?

I'm facing an issue trying to retrieve product data from a JSON file. Despite attempting different methods and searching for solutions online, I have not been able to find one that fits my specific scenario. As I am new to both Vue and axios, I apprec ...

Display the number of items that have been filtered as soon as the Mixitup page loads

Currently, I am utilizing MixItUp 3 for sorting and filtering items, with the goal of displaying the count of items within each filter category upon the initial page load. Despite attempting a solution found on SO (mixitup counting visible items on initial ...

What are the steps to achieve consistent response behavior in POSTMAN that matches that of a web browser?

Below is an example of my code: const express = require('express'); const app = express(); app.get('/', function (req, res) { res.setHeader('Content-Type', 'text/html'); res.write("First \n"); set ...

Having trouble sending a POST request to a nested array in Express JS

Welcome, this is my first post here so feel free to point out any missing information or incomplete details in my question :) I am currently working on a project where I need to make a POST request to an array within my data structure called features: co ...

Steps to insert a personalized attribute into a TypeScript interface

UPDATED EXPLANATION: I'm fairly new to TypeScript, so please bear with me if this question seems basic. I'm working with an existing library (ngx-logger) that I don't want to or can't modify. My goal is to create a service that generat ...

Generate a new document and input information using the ionic framework

I'm currently working on an application for mapping purposes. I have generated KML and JSON strings that need to be stored in files within the phone's memory. To achieve this, I implemented the following code: var fileObject; document.addEve ...

Best method for combining objects in a tidy manner

I have multiple objects with similar structures, where some have null values for certain fields and one object (obj2) has values for those fields that are null in the others. I want to merge them and consider the values from obj2: var obj2 = { options ...

Having trouble establishing a connection between MongoDB and a Node.js Express server on my local machine

While attempting to establish a connection between mongoDB and nodejs express using the post method, I added a logger that should display a message confirming that the database is connected once nodejs listens to mongoDB. However, I encountered an issue wh ...

Ways to ensure your Javascript code only runs based on the specific browser

I need a Javascript code to run depending on the browser version. Specifically, if the browser is not IE or is IE 9+, one piece of Javascript should be executed. If the browser is IE8 or lower, another piece of Javascript should be executed. My attempt to ...

Guide on looping through deeply nested children within an object to accumulate a list of names

Within an object, there are numerous parent and child elements var obj={ name: 'one', child:{ name: 'two', child:{ name: 'three', child.. } } } foo(obj) Create a ...

When accessing a page from a link, JavaScript sometimes does not immediately execute on the first attempt

I'm encountering a strange issue in my rails application, where a template fails to execute the Javascript code the first time it is loaded via a link on my home page. This problem only occurs when accessed through the link for the first time. I' ...