How to effectively share an object array between controllers when utilizing modal windows in AngularJS

I'm currently working with an array of objects that I need to share between two controllers, one of which involves a modal window.

Check out the JavaScript code below:

angular.module('MyApp', ['ngMaterial', 'ngMessages', 'material.svgAssetsCache', 'ui.bootstrap'])
  .service('Faq', function ($http) {
    this.faqList = [];
    this.faqList = $http.get('/Json/faq.json');

    this.getFaqs = function ()
    {
        return this.faqList;
    }

    this.addfaq = function (obj) {
        this.faqList.push(obj);
    };


})
.controller('AppCtrl', function ($scope,$modal,Faq) {



    $scope.faqData = [];

    Faq.getFaqs().then(function (msg) {
        $scope.faqData = msg.data;

    });

    }

    $scope.show = function () {
        $modal.open({
            templateUrl: "faqAddUpdate.html",
            controller: "faqctrl"
        });
    };


})
.controller('faqctrl', function ($scope, $modalInstance, Faq) {
    $scope.question = '';
    $scope.id = '';
    $scope.answer = '';

    $scope.editFaq = function (id) {
        $scope.divFaq = true;
        $scope.faqs = [];
        Faq.getData().then(function (msg) {
            $scope.faqs = msg.data;
            var l = $scope.faqs.length;
            for (var i = 0; i < l; i++) {
                if ($scope.faqs[i].id == id) {
                    $scope.question = $scope.faqs[i].question;
                    $scope.id = $scope.faqs[i].id;
                    $scope.answer = $scope.faqs[i].answer;

                }
            }
        });
    };


    $scope.AddUpdateFAQ = function () {
        var faq = {
            id: $scope.id,
            question: $scope.question,
            answer: $scope.answer
        };
        Faq.addfaq(faq);
        console.log(faq);
        $modalInstance.close();
    };

    $scope.Cancel = function () {
        $modalInstance.dismiss();
    };
});

However, when trying to submit data through the modal, it returns an error stating that this.faqList.push is not a function.

Answer №1

The issue lies in the fact that your faqList variable is not being assigned an array.

You are replacing the original definition with:

this.faqList = [];

Instead of:

this.faqList = $http.get('/Json/faq.json');

Keep in mind that $http.get returns a promise, not an array (refer to documentation).

To resolve this problem, you should modify your code like so:

this.faqList = [];
$http.get('/Json/faq.json').then(function(result) {
  // processing of results should be done here
  this.faqList = result.data;
});

Answer №2

Haven't tested it out, but it seems like this is only accessible within the function scope. To address this issue, creating a variable _this first might be beneficial:


this.bookmarks = [];
this.bookmarks = $http.get('/Json/bookmarks.json');
var _this = this;

this.getBookmarks = function () {
    return _this.bookmarks;
}

this.addBookmark = function (item) {
    _this.bookmarks.push(item);
};

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

Incorporating Paged.JS functionality into a React/JS web application

My attempt to showcase my html page using paged.js in a react project has hit a snag. The html loads perfectly when accessed from local host (not via npm start, but the live server extension on vscode). However, following the steps outlined on this website ...

Discover the best way to retrieve attribute values using jQuery

I'm struggling to retrieve the value of the attribute "_last_val" from my input, but I'm having trouble getting it. Here is what I have attempted: demo // Here is the HTML code <form method="post" action="" id="feedback_form"> <inpu ...

JSP page displaying a table with a text input field named "code" enclosed within <TD> tags

Recently, I designed a JSP page that features a table with two columns: Code and Description. The table data is an input type of "text" with the name attribute set to "code". The main functionality I need to implement is the automatic generation of the d ...

Running 'Grunt Serve' is successful, but encountering issues with 'Grunt Build/Upload' when working on a static site

I'm encountering an issue with a Grunt build that I put together. The Challenge Everything runs smoothly locally when I execute grunt serve. However, after running grunt build and syncing the content to my S3 bucket, the ng-view pages don't ren ...

Are your JavaScript scripts causing conflicts?

My bootstrap Carousel was working perfectly fine until I added a script to modify the navigation bars. The original script for the Carousel looked like this: <script> !function ($) { $(function() { $('#myCar ...

Encountered an error with the opcode during deployment of migrations

Encountering an error while running the truffle migration command, despite trying several solutions without success. PS C:\Users\Jatin\OneDrive - nsut.ac.in\Desktop\Truffle\web> truffle migration Compiling your contracts... ...

How can I add an SVG tooltip that appears when I hover my

I have successfully implemented an SVG map showing marked locations and polygons, with CSS styling that makes the areas stand out on hover. I achieved this without using any JavaScript code. My next goal is to create a hovering window or tooltip that disp ...

Looking for a solution to organize the dynamically generated list items in an HTML page

I am currently working on a movie listing website where all the movies are displayed in sequence based on their #TITLE#. The webpage is generated automatically by the software using a template file. Here is the section of code in the template file that sho ...

Using Array.push within a promise chain can produce unexpected results

I have developed a method that is supposed to retrieve a list of devices connected to the network that the client has access to. export const connectedDevicesCore = (vpnId: string, vpnAuthToken: string) => Service.listVPNConnectionsCore ...

The importance of context visibility for functions in JavaScript within a React.js environment

Why is it that the react state is visible in the function handleFinishChange, but cannot be seen in validationFinishTime? Both are passed to the component InputFieldForm. When executing this code, an error of Uncaught TypeError: Cannot read property ' ...

Tips for creating a fixed footer that adjusts with a flexible wrapper

Feeling incredibly stressed, I embarked on a quest to find the perfect sticky footer. After searching Google for what seemed like an eternity, I came across multiple tutorials recommending the use of min-height:100%. However, this approach caused the wrap ...

What is the best way to ensure there is only one instance of a React component visible at any given time?

In my current project with React, I am working on implementing a specific functionality. The challenge I am facing involves three components: ComponentA, ComponentB, and ComponentC. The twist is that ComponentC can be rendered as a child of either Compone ...

Tips for retrieving arguments within a method called from a template in vue.js?

Here is an example where I am attempting to call a method from the template and pass in some arguments. How can I access those arguments from within the method? Snippet from script: methods: { showBinaries(job, id) { let test_url = process.en ...

Modify the class name of the clicked button and another button when a button is clicked in ReactJs

I have a React component that displays two buttons. When the user clicks on the left button, it should change the class of both buttons and render the ListView component. Similarly, when the user clicks on the right button, it should change the class of bo ...

How can I enhance data from an AJAX callback in Mapbox with an additional layer?

With the code snippet below, I am aiming to utilize event data from an API to create a mapbox layer. This layer will be used to place markers and symbols on the map. However, I prefer not to use Mapbox markers as they cause issues with my code. I have suc ...

How can you make a button in Vue only visible after all API calls have successfully retrieved the data?

Is there a way to make the report button visible only after all the data has been loaded from the latest click of the budget button? Currently, when the budget button is clicked, it retrieves budgets and displays them in a Vue grid using Kendo Grid. To spe ...

issues encountered with sending a multidimensional array using ajax, specifically with the index[0]

I'm struggling with sending a multidimensional array from PHP to Javascript/jQuery, encountering a peculiar issue. Upon transmitting index 0 through json_encode($array);, the desired response format is successfully received by the client: [[0,0],[1, ...

The images in the React slick carousel appear to be slightly out of

I'm experiencing blurriness in my carousel when it animates with card items. Despite searching for a solution, I haven't found one yet. My tech stack includes Next.js and TypeScript. const ref = useRef<any>(); const settings = { arro ...

Submitting an ajax form with the use of the symbol '&'

I am currently working on a form submission using the .ajax() method. Within my script, I have the following code: data: dataString, The variable dataString is composed of: var list = $('.listsummary').val() The listsummary class is assoc ...

Updating textures dynamically in Three.js

My current project involves creating a user interface where users can change the texture of a selected object by clicking on the desired texture image. However, I am facing a challenge where I can only access and use the last texture added in the array. ...