Tips for effectively passing a $scope object between various controllers

I am encountering an issue with sharing a $scope object between two controllers.

Within the 'IssueBookCtrl' controller, I update the 'books' object element value like this:

$scope.books[i].issued = true;

After that, I use the $emit service to share the $scope object with the 'BookListCtrl_Librarian' controller.

$scope.$emit('update_parent_controller', $scope.books);

However, when I view the page associated with the 'BookListCtrl_Librarian' controller, I do not see the updated object.

In the controller.js file:

Controllers.controller('BookListCtrl_Librarian', ['$scope','$http','$location','$rootScope','BookData',
function ($scope, $http ,$location, $rootScope , BookData) {
    $http.get('data/books.json').success(function(data) {
    if($rootScope.books==='undefined'){
        $rootScope.books = BookData.getData();
    }
        $scope.books = data;
    });
    $scope.options = ['bookId', 'cost'];

    $scope.$on("update_parent_controller", function(event, books){
        $scope.books = books;
    });

    // Other functions defined here...

}]);

Controllers.controller('IssueBookCtrl', ['$scope','$rootScope','$http','$routeParams','$location',
function ($scope,$rootScope, $http, $routeParams, $location) {
    var Id=$routeParams.bookId;
    $http.get('data/books.json').success(function(data) {
        $scope.books = data;
    });

    // Issue and other functions defined here...

}]);

Your guidance on this matter would be greatly appreciated.

Thank you!

Answer №1

Hey there! When you're faced with this situation, make sure to utilize rootscope instead of scope emit.

$rootScope.$emit('send_data_to_parent', $scope.info);

Then, in another controller:

$rootScope.$on('send_data_to_parent', function(event, info){
    $scope.info = info;
});

Answer №2

One approach is to trigger a digest cycle after making changes to a model:

$scope.$apply();

Alternatively, it is advisable to create a Books service to manage shared models and logic. More information on creating custom services can be found here.

Another solution is to nest controllers (place one inside another) so that the inner controller has access to the outer controller's models using the $parent variable.

By utilizing either of these methods, you should not encounter any issues with object updates as AngularJS performs dirty-checks whenever scope variables are modified.

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

Retrieving AJAX content once it has finished loading

Apologies for my poor English. I have a function to handle ajax requests like this: $(document).on("click", ".ajax", function(e){ //dynamic content here, getting the href value from links. }); Now I need to manipulate the content of the ajax response AF ...

Is there a way to apply the style property only when a component is hovered in Next.js?

I would like the ability to hover over a component and have it display with unique CSS characteristics. For instance, if I hover on item A, I only want item A to stand out from the rest. Currently, I am using this method of changing the element's bac ...

Worldwide Angular-formly validations

I have integrated angular formly-forms into multiple HTML pages in my App, with validation being a key feature: { className: 'col-xs-5', key: 'poc', ...

Using TypeScript to automatically determine the argument type of a function by analyzing the return type of a different function

I am working on an interface with the following structure: interface Res<R = any> { first?(): Promise<R>; second(arg: { response: R }): void; } However, I noticed that when creating a plain object based on this interface, the response ...

Transitioning the Background Image is a common design technique

After spending hours trying to figure out how to make my background "jumbotron" change images smoothly with a transition, I am still stuck. I have tried both internal scripts and JavaScript, but nothing seems to work. Is there any way to achieve this witho ...

What is the solution for displaying just a single panel?

Is there a way to ensure that only the hidden text is displayed when clicking on the button within each panel? Currently, both panels are being revealed simultaneously... import React, { useState } from "react"; import "./styles.css"; export default func ...

What's the issue with my jQuery AJAX script?

I am experiencing an issue with my ajax pages using jQuery to retrieve content. Only one page seems to be working properly, even though I have multiple pages set up. How can I resolve this problem? $(document).ready(function() { $('.lazy_content& ...

Transform an AngularJS application into a conventional Node.js application for seamless deployment on Node.js hosting platforms

Excuse my lack of experience, but I am looking to make my AngularJS app deployment-friendly with any Node.js hosting platform. I came across something similar for Meteor: "https://github.com/onmodulus/demeteorizer" but haven't found anything equivale ...

Is it possible to make changes to dynamically inserted HTML using jQuery.ajax?

I'm facing a scenario in jQuery where I make an ajax call that inserts HTML into my website. However, I also need to perform operations on this inserted HTML within the same ajax call's success callback function. Here is a simplified version of ...

Ways to dynamically insert a new row into a table based on user input in a Postman-like reactive table

Is there a way to dynamically insert a row when a single character is entered into an input field in the header tab, similar to how Postman functions? 1) If a user types any single character in the td of the first row, then a new row should be added below ...

What is the best way to show an SVG icon in React without having to make an HTTP request for the file?

A special requirement for a react application is to display icons in certain parts of the application while offline. The use of inline svg is particularly fitting for this purpose. import React from 'react'; // Utilizing inline svg to showcase i ...

I'm having trouble displaying the result of my calculation in the code. Could it be because I forgot to include an output tag?

I am attempting to develop a Miles Per Gallon (MPG) calculator using Javascript. However, I'm encountering difficulties with displaying the results once the "Calculate" button is pressed. <html> <head> <title> MPG Calculator </ti ...

What are the reasons behind lang sass not functioning within the style tag of a .vue file?

Even though I had previously installed sass-loader and node-sass in my project, I encountered an issue when attempting to use <style lang="sass"> in my vue file. The style did not compile as expected, however it worked perfectly without the lang="s ...

The Express application fails to receive a response from a Mongodb query function

In my current project, I am implementing a simple API Key authentication system. The main goal is to validate the provided key against the user's input. There is a separate file containing a function that queries the database and returns either true/ ...

Saving a MongoDB document within an array in Node.js and retrieving it

I am working on retrieving specific documents from MongoDB using Node.js and storing them in an array. const getStockComments = async (req) => { const stockname = req.params.stockName; var comments = []; var data = []; const stock = await sto ...

Is it possible to prevent copying dates within tabs using Angular-UI Bootstrap?

I have set up a basic Tab using Angular-ui bootstrap. Within the tab, there is a 'date input' <input type="date"/> <tabset> <tab heading="Tab A"> Date Input Inside Tab</br> Date 1:<input type="dat ...

Adding a button in Node and Mongoose for updating data: A step-by-step guide

I have set up a mongoose database containing events, each event is displayed within a bootstrap card. My challenge now is to find a way to redirect the admin to a page where they can update the event card and save it to my mongoose db. The problem I' ...

Tips for retrieving the selected option from a dropdown menu

I have a dropdown menu with checkboxes that can be selected using SumoSelect. Here is the markup for the dropdown menu: <select multiple="multiple" name="somename" id="uq" class="select"> <option value="volvo">Volvo</option> <o ...

The AngularJS array data is not displaying correctly

I am having trouble displaying comments array data in HTML properly. The data appears the same as it is in the comments array. What could be causing this issue? How should I proceed? <ul class="media-list" ng-controller="dishDetailController as menuCt ...

What could be preventing $routeChangeSuccess from being called?

I have been working on a similar feature for my app, but I'm struggling to capture the routeChangeSuccess event. var myapp = angular.module('myapp', ["ui.router", "ngRoute"]); myapp.controller("home.RootController", function($rootScope, ...