Having trouble with my custom AngularJs service created using the factory method

Discovering a challenge with my current setup. I have implemented two separate controllers that handle adding 'country name' and 'price' to a list. Everything functions as expected when each button is clicked individually. However, when two buttons are randomly selected, the desired functionality is not achieved. I am utilizing a factory to create a custom service to address this issue. Below is a snippet of the code. Any insights on where I may have gone wrong or if something is overlooked would be greatly appreciated. Thank you.

(function() {
  angular.module("customServiceApp", []).controller("westernCountriesController", westernCountriesControllerFunction).controller("asianCountriesController", asianCountriesControllerFunction).factory("serviceFactory", serviceFactoryController);

  function serviceFactoryController() {
    var serviceFactory = function(total) {
      return new countriesService(total);
    };
    return serviceFactory;
  }

  function countriesService(total) {
    service = this;
    service.travelPackage = [];
    service.addCountries = function(name, price) {
      var countryTravelDetail = {
        name: name,
        price: price
      }
      if (service.travelPackage.length < total) {
        service.travelPackage.push(countryTravelDetail);
      } else {
        throw Error("You cannot select more than " + total + " countries");
      }
    }
    service.allTravelCountries = function() {
      return service.travelPackage;
    }
  }
  westernCountriesControllerFunction.$inject = ["serviceFactory"]

  function westernCountriesControllerFunction(serviceFactory) {
    var westTravel = this;
    var service = serviceFactory(2);
    westTravel.addCountry = function() {
      try {
        service.addCountries(westTravel.countryName, westTravel.countryPrice);
      } catch (error) {
        westTravel.errorMessage = error.message;
      }
      westTravel.showAllCountries = service.allTravelCountries();
    }
  }
  asianCountriesControllerFunction.$inject = ["serviceFactory"];

  function asianCountriesControllerFunction(serviceFactory) {
    var asiaTravel = this;
    var service = serviceFactory(3);
    asiaTravel.addCountry = function() {
      try {
        service.addCountries(asiaTravel.countryName, asiaTravel.countryPrice);
      } catch (error) {
        asiaTravel.errorMessage = error.message;
      }
      asiaTravel.displayCountries = service.allTravelCountries();
    }
  }
})();
<!DOCTYPE html>
<html ng-app="customServiceApp">

<head>
  <meta charset="utf-8">
  <meta name="description" content="First Angular App">
  <meta name="keywords" content="HTML, Javascript, AngularJs">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://code.angularjs.org/1.6.1/angular.min.js"></script>
  <script src="app.js"></script>
  <title>Custom Angular Service</title>
</head>

<body>
  <div ng-controller="asianCountriesController as asiaTravel">
    <input type="text" placeholder="Country Name" ng-model="asiaTravel.countryName">
    <input type="text" placeholder="Country Price" ng-model="asiaTravel.countryPrice">
    <input type="button" value="Add Asian Countries" ng-click="asiaTravel.addCountry();">
    <ul>
      <li ng-repeat="asianCountry in asiaTravel.displayCountries">Country Name : {{asianCountry.name}} and Price is : {{asianCountry.price}}</li>
    </ul>
    <div ng-if({{asiaTravel.errorMessage !=null}})>{{asiaTravel.errorMessage}}</div>
  </div>
  <div ng-controller="westernCountriesController as westTravel">
    <input type="text" placeholder="Country Name" ng-model="westTravel.countryName">
    <input type="text" placeholder="Country Price" ng-model="westTravel.countryPrice">
    <input type="button" value="Add Western Countries" ng-click="westTravel.addCountry();">
    <div ng-repeat="westernCountry in westTravel.showAllCountries">Western country selected is: {{westernCountry.name}} and the price is : {{westernCountry.price}}</div>
    <div ng-if({{westTravel.errorMessage !=null}})>{{westTravel.errorMessage}}</div>
  </div>
</body>

</html>

Answer №1

instance = this; - saving this to a global variable. As a result, when the service is called again, the previous value is replaced.

You may want to consider implementing this approach (in countriesService):

var instance = this; 

.... // add your logic here.

return instance; 

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

Issues arise in Ionic 3 when attempting to use scripts or external custom jQuery plugins within inner pages

When I utilize a script tag in my index.HTML file, it functions properly on the initial or root pages of Ionic 3. However, upon navigating to other pages using NavController, the script ceases to work on these inner pages. How can I implement a custom jQ ...

Transitioning to Material-ui Version 4

During the process of upgrading material-ui in my React Application from version 3.9.3 to version 4.3.2, I encountered an error message stating TypeError: styles_1.createGenerateClassName is not a function. I am feeling lost when it comes to transitioning ...

Angular's implementation of a web socket connection

I am facing an issue with my Angular project where the web socket connection only opens upon page reload, and not when initially accessed. My goal is to have the socket start as soon as a user logs in, and close when they log out. Here is the custom socke ...

JavaScript - Automatic memory management following the execution of functions

After doing some research on garbage collection in JavaScript, I came across information stating that local variables of functions are collected once the function has returned (except for cyclical references which require breaking circles for the GC to fun ...

`Can you provide instructions on modifying CSS using JavaScript once the window size reaches a specified threshold?`

Is there a way to use JavaScript to automatically adjust the font size when the screen reaches 1050px? ...

Using deconstruction in exporting as default

As I was diving into a new codebase, I stumbled upon this interesting setup: //index.js export { default } from './Tabs' export { default as Tab } from './Tab' //Tab.js export default class Tab extends Component { render() => &ap ...

Tips for generating an HTML template as a string using jQuery

I have developed a dynamic modal using plain JavaScript, triggered by a button click. This modal is controlled based on the attributes `data-open-hours` and `data-closed-hours` in the HTML. If you take a look at my demo, you will notice an issue. Let me e ...

Is the text in the React chat application too lengthy causing a bug problem?

In my chat application built with React, I am facing an issue where if a user types more than 100 characters, the message gets cut off. How can I fix this problem? Please refer to the image below for reference. https://i.sstatic.net/DLNyH.png {Object.keys ...

Unable to retrieve the loggedIn value from express.session in a Node.js application

After creating a web application using nodejs and sequelize as the ORM for mysql, I encountered an issue with the loggedIn parameter being undefined when accessing it in different routes despite implementing login functionality with express-session. Here ...

Is it possible to have multiple divs with unique IDs that can be individually controlled using a single JavaScript function?

I'm in the process of figuring out how to create a single JavaScript function that can manage multiple divs. I currently have several divs with distinct ids and I've written separate JavaScript functions for each one. However, they either do not ...

What is the best way to transfer the value of a radio button, retrieved from a database, to a textbox?

Greetings, I am trying to figure out how to pass the value of a radio button to a textbox using jQuery and PHP. The radio buttons are generated dynamically based on rows from my database, so I set the row ID as the ID for each radio button. However, the co ...

Discover the joy of reading with wrap/unwrap to consume more content in less

I am experimenting with a 'read-more read-less' feature using a wrap method that currently only works for the 'show more' functionality. So, to clarify, if the text exceeds a certain length, I truncate it and insert a read-more-link ( ...

Adding static files to your HTML page with node.js

This is not a question about using express.static() In my application, I have multiple pages that share the same JS and CSS dependencies. Instead of adding <script> or <link> tags to every single page, I'm looking for a way to include the ...

`Finding it difficult to halt the spread of events in reactJs`

One of my conditions involves a simple dropdown menu: handleDropdown = (e) => { if (e.type === "focus") { console.log("inside dropdown focus"); this.setState({ dropDownDis: "block" }) } else if (e.type === "blur") { console.lo ...

What is the best way to align grid elements vertically instead of horizontally on mobile devices using JQuery Mobile?

I've created a basic JQuery Mobile website with a grid containing four horizontally aligned blocks, each with text and a button. While it displays well on desktop browsers, the blocks appear cramped when viewed on my Android Galaxy phone in landscape ...

Using jQuery to Iterate Through an AJAX Response

I'm working on a tagger application. When a user submits a tag, ajax sends the following response: {"returnmessage":"The Ajax operation was successful.","tagsinserted":"BLAH, BLOOOW","returncode":"0"} My goal is to extract the tags inserted and dyna ...

mention the element to display on the pagination

I find the logic here quite puzzling. This particular code block seems to be related to pagination, as it involves a function that is triggered upon clicking. componentDidUpdate() { const { location } = this.context; const { query } = this; if ...

Guide on implementing a redirect to a different page following form submission with the inclusion of a loading screen

<form action='page.html' method='post'> <input type="text" name="name" placeholder="Enter your name here"> <input type="submit" value="submit"> </form> The cod ...

Multiple uses of p-fileUpload in primeng are not functioning as expected

Let me explain the situation with this component. I have defined it as follows: <p-fileUpload #fileUpload accept=".csv,.txt" maxFileSize="1000000" customUpload="true" (uploadHandler)="uploadFile($event)"> In my package Json file, I have specified: ...

When working with Typescript, the error "Unable to locate type 'require'" may be encountered

I am attempting to incorporate the type definition file available at https://www.npmjs.com/package/diff-match-patch into my Angularjs project. Just a heads up: I am working with Visual Studio as my IDE var DiffMatchPatch = require('diff-match-patch& ...