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

JavaScript Equivalent of jQuery's removeClass and addClass Functions

I am faced with the challenge of rewriting the following code without using jQuery: document.querySelector('.loading-overlay').classList.remove('hidden'); Can anyone provide guidance on how this can be achieved? ...

Using Vue.js to set both v-model and v-bind:value on one input element

I have a React component that has a form for submitting user information. The main issue I'm facing is setting a default value in the input field. When the page loads, I want the input field to display the user's existing email address by defaul ...

Stop Ajax from activating jQuery function

Upon examining our Drupal site, we discovered a straightforward jQuery script that inserts a div class containing content: (function($) { Drupal.behaviors.myHelpText = { attach: function (context, settings) { //code begins //adjusting placeholder ...

What could be the reason for my post jQuery Ajax request sending JSON data?

After downloading some code, I came across the following fragment: function FetchCommentsBySessionIDWCF_JSON() { varType = "POST"; varUrl = "service/CommentSessionIDWCFService.svc/FetchCommentsByPost"; varData = ' ...

cross-domain ajax response

Imagine a unique scenario that will pique the interest of many developers. You have a JavaScript file and a PHP file - in the JS file, you've coded AJAX to send parameters via HTTP request to the PHP file and receive a response. Now, let's delve ...

Exploring AngularJS: Leveraging ng-model within a custom directive featuring iterations and dynamically generated HTML elements

Trying to implement a directive for a grid, I encountered an issue where passing in a column definition that includes an HTML control with ng-model and ng-click directives resulted in an error: "Error: [$rootScope:infdig] 10 $digest() iterations reached. ...

Where is the destination of the response in a Client-Side API Call?

I have developed an API that accepts a person's name and provides information about them in return. To simplify the usage of my API for third parties on their websites, I have decided to create a JavaScript widget that can be embedded using a script ...

Navigating JSON Data in Groovy Using a Loop: A Handy Guide

Just starting out with Groovy and attempting to mock a service in SoapUI. The task at hand involves loading a text file containing JSON data, and then matching that data to a specific node. Here is what I have attempted so far: def inputFile = new File( ...

Guide to testing Vuex Mutations with Vue-test-utils and Jest

I have reviewed a few tutorials on mocking and testing Vuex actions, but I have struggled to implement them successfully on my own. Despite following the steps outlined in the links provided, I consistently encountered an issue where toHaveBeenCalled would ...

What are the steps to implementing a JavaScript WebWorker in a webpack environment?

Struggling to implement web workers in my web app and encountering difficulties. The addition of a new entry to the webpack.config.js file is not producing desired results. Attempting to utilize the npm package named worker-loader, however, facing challen ...

Prepare an email message for sending

Currently, I'm working on an app using officejs. My goal is to extract content from an Excel worksheet and insert it into an Outlook email. However, I don't want the email to be automatically sent by the system. Instead, I would like the new emai ...

Tips for retrieving return values from AJAX URL content

As I am writing some code to send data from one page to another through the ajax URL, I encountered an issue where the retrieved values on the previous page are showing as null. The first page code looks like this: <script> function myFunction() { ...

Nodejs application crashes due to buffer creation issues

router.post('/image', multipartMiddleware , function(req, res) { var file_name = req.body.name; var data = req.body.data; var stream = fs.createReadStream(data); //issue arises here return s3fsImpl.writeFile(file_name , stream).t ...

Using AngularJS ng-options with templates embedded within

I am trying to enhance a dropdown select by adding text and an icon to it. This is my starting point: <select ng-change="actions.change()" ng-model="variant_id" ng-options='variant.id as variant.name for variant in variants'&g ...

Incorporate JSON data using jQuery's AJAX in MVC3

I need assistance with parsing the JSON data retrieved from a webservice through my controller. Currently, I am displaying the entire JSON string in a div as text. However, I only want to extract specific values such as "color" and "size". I am unsure of ...

Encountering an Invariant Violation: React does not allow objects to be used as children

I can't figure out why my code isn't working. Every time I run it, I get the error message: Invariant Violation: Objects are not valid as a React child (found: object with keys {_40, _65, _55, _72}). If you meant to render a collection of chil ...

What is the reason for the clearInterval consistently functioning after the completion of the function?

Just starting out in web programming and currently delving into javascript and jquery ajax.. This snippet represents my javascript code. The refresh variable controls an interval for updating the chat by fetching chats from the database and displaying the ...

Utilizing a Meteor Method within a Promise Handler [Halting without Throwing an Error]

I've been working on integrating the Gumroad-API NPM package into my Meteor app, but I've run into some server-side issues. Specifically, when attempting to make a Meteor method call or insert data into a collection within a Promise callback. Be ...

Encountered a "no login transports available" error while trying to use Firebase

Currently utilizing Firebase's AngularFire for Facebook logins and encountering an issue with the provided code. Below is my HTML code (including ng-click to initiate login): <a ng-click="loginWithFacebook()" class="btn btn-block btn-social btn- ...

Display only a loading image with a see-through background after submitting the page

After submitting the page, I would like to display a loading image in the middle of the page with a transparent background. The current styling code I have used is as follows: #loading { position: fixed; top: 50%; left: 50%; z-index: 1104; ...