Unable to access model content in multiple AngularJS controllers

My question is clear and straightforward. Let me explain in detail: 1. I have created a module.

var ang = angular.module('myApp', []);

  1. I have a controller named controller1, which includes the 'campaign' factory.

//controllerone.js

ang.controller('controller1', function(campaign){
   $scope.campaigns = new campaign();
   //The entire campaign object with data is displayed here, please refer to Image 1 attached
   console.log($scope.campaigns); 
});
ang.factory('campaign', function($http){
  var campaign = function(){
    this.timePeriodList = buildTimePeriodList();
    ...
    ...
    this.campaignList = [];

 };
Campaigns.prototype.fetchCampaigns = function() {
  //Service call to populate the data in this.campaignList
};
});

Now when trying to use the same campaign factory in the second controller, only the object structure is retrieved without any data.

//controlertwo.js

ang.controller('controller2', function(campaign){
   $scope.campaigns = new campaign();
   //Only the structure of the campaign object is shown, but no data for campaignList, see image 2 attached
   console.log($scope.campaigns); 
});

Since the factory service is a singleton object, I expected the same result as in controllerone.js,

Image 1:

Image 2:

Answer №1

When working with an angular factory, I recommend taking a different approach. Avoid attaching anything to the Prototype of an object. Instead, create an object within the scope of your angular factory, attach the desired elements to it, and then return it. For instance:

     ang.factory('campaign', function ($http) {
var campaign = {};
campaign.method1 = function () {
    //..
}
campaign.campaignList = [];
//...

campaign.fetchCampaigns = function () {
    //Service call to populate the data in this.campaignList
};

});

//Then, if campaign is injected into your controllers, you can utilize it like this:

ang.controller('controller2', function (campaign) {
    campaign.fetchCampaigns();// This will populate the list and keep it filled for other controllers to use...
    console.log(compaign.campaignList);
});

Avoid exposing any elements outside of the factory by not attaching them to the campaign object.

Answer №2

Establish a campaign within a service. For example, use the campaignService.

Code has been updated---

var ang = angular.module('myApp', []);

ang.service('campaignService', function($scope){
    var campaign = function(){
        this.timePeriodList = buildTimePeriodList();
        ...
        ...
        this.campaignList = [];
    }
    return campaign;
});

ang.controller("controller1", ["campaignService",
function($scope, $rootScope, campaignService){
    $scope.campaigns=campaignService.campaign();
}
]);

ang.controller("controller2", ["campaignService",
function($scope, $rootScope, campaignService){
    $scope.campaigns=campaignService.campaign();
    console.log($scope.campaigns);
}
]);

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

Flask - Refreshing Forms Dynamically

In an effort to enhance the responsiveness of my app, I am looking for a way to prevent the page from reloading every time a POST request is sent. My current setup includes a dynamically generated form with input fields designed like this: <div class=&q ...

Grouping elements of an array of objects in JavaScript

I've been struggling to categorize elements with similar values in the array for quite some time, but I seem to be stuck Array: list = [ {id: "0", created_at: "foo1", value: "35"}, {id: "1", created_at: "foo1", value: "26"}, {id: "2", cr ...

Storing references to the DOM elements external to the rendering component

Just diving into the world of Electron + Typescript, so please bear with me. Currently, I'm experimenting with what can be achieved within Electron. Issue: My goal is to manipulate DOM elements outside of the renderer. I pass a button as a parameter ...

Dynamically updating fields in PHP using jQuery's passed variable

In my web application, I have a selection of locker numbers available in a dropdown list that is populated from MYSQL/PHP. My goal is to display each locker's combination and location when a user selects a locker number from the dropdown list on the s ...

What is the best way to test the validity of a form while also verifying email availability?

I am currently working on implementing async validation in reactive forms. My goal is to disable the submit button whenever a new input is provided. However, I am facing an issue where if duplicate emails are entered, the form remains valid for a brief per ...

Retrieve the total number of hours within a designated time frame that falls within a different time frame

Having a difficult time with this, let me present you with a scenario: A waiter at a restaurant earns $15/hour, but between 9:00 PM and 2:30 AM, he gets paid an additional $3/hour. I have the 'start' and 'end' of the shift as Date obje ...

Angular, JavaScript, and PHP are three powerful programming languages that

This file contains HTML code <ul class="list"> <li id="numword" data-score="{{item.score}}" class="" ng-repeat="item in words track by $index"> {{item.word}} {{item.score}} </li> </ul> Here is the visual representa ...

Utilizing JavaScript to Load and Showcase Images from a Temporary Image to imgsrc

How can I dynamically display images from the temporary image array 'tempimages' onto the 'img' element with the 'src' property? I have written a code that attempts to display temporary images from 'tempimages[]' on ...

Tips for resolving the issue: "Encountered error loading module script..." in Angular 8 and Electron 5

I have been working on developing an Electron 5 app using Angular 8. Despite following numerous online tutorials, I keep encountering the same error. Initially, I set up a new project and ran ng serve --open, which successfully displayed the default angul ...

Error in React-Native: Unable to locate main project file during the build process

Just integrated cocoapods into a React Native project. After a successful build, RN is throwing this error... https://i.stack.imgur.com/czn2W.png No errors in Xcode during the build process, but Xcode is displaying these warnings https://i.stack.imgur.c ...

"Troubleshooting when a NodeJS Program Refuses to

Currently facing an issue while attempting to execute a Node program written in JavaScript with no indication of what's causing the problem. The program abruptly ends without providing any error or stack trace. const prompt = require('prompt-sync ...

Is there a way to implement word wrapping in li text without making any changes to its width

Is there a method to wrap the content inside li elements without modifying their width? As an illustration, consider the following structure - <ul> <li>Text Example</li> <li>Text Example</li> <li>Text Exampl ...

JavaScript: Developing an interactive Word Guessing Game

Here's some sample code: let ccdisplay = document.querySelector('.crrDisplay'); let incdisplay = document.querySelector('.incDisplay'); let guess = document.querySelector('#character'); let textForm = document.q ...

Troubleshooting the issue of a callback function not properly updating state within the componentDidMount

I am currently utilizing Next.js and have the following functions implemented: componentDidMount = () => { //Retrieves cart from storage let self = this this.updateCart(Store.getCart(), self) ... } updateCart = (cart, self) => { ...

Is it possible to initiate a series of node tasks in a predetermined sequence?

I have developed a framework that currently requires 4 user inputs to install, which is quite cumbersome. I am looking for a way to streamline the process to just one input. Essentially, I am seeking a solution to execute those 4 commands with only one in ...

The issue of 'position: fixed' not properly functioning within the Materialize CSS modal

My goal is to have the header of the Modal stay fixed while scrolling, but for some reason, the option position:fixed; is not working. I am currently using Materialize CSS to build the modal and surprisingly, position:sticky; is working. $(document).rea ...

Verifying the visibility of an element

I am facing a challenge with a list of apps displayed on a non-angular page. The availability of these apps depends on the subscription level purchased by the user. Even if an app has not been purchased, it is still listed but displayed with an overlay (pl ...

`How can I extract HTMLElements from slots in vue3?`

When attempting to develop a Layer component, I encountered some challenges. Here is the code: // Wrapper.vue <template> <slot v-bind="attrs"></slot> </template> <script lang="ts" setup> import { defi ...

Validation customized through offspring control

Currently, I am dealing with a situation where I need to transclude all controls within a directive that has its own form element and buttons. The model in this context includes a property for the total capacity and another property that consists of compar ...

What is the best way to prevent duplicates in a Material-UI dropzone area?

Currently, I am utilizing the Material-UI Dropzone component from https://yuvaleros.github.io/material-ui-dropzone/ and my goal is to prevent users from uploading duplicate files that have been previously uploaded. I attempted using an onchange function t ...