What is the best way to merge angularjs modules?

In my angularjs application using the codeigniter PHP framework, I have implemented 3 modules - cars.js for car details, cellphones.js for cellphone details, and home.js for home details. Each module caters to a different client's needs.

I am trying to compare the total estimation price of selected items but have not been successful with angularjs $cookies so far. Here is an overview of what I am trying to achieve:

To simplify, I will explain by adding a basic controller to each app with some sample data. Each JSON array contains prices and includes a checkbox to add items to the estimate. When a user checks the box, the item should be added to the estimated list, and the total amount should adjust accordingly. This example aims to demonstrate how to integrate multiple angularjs apps and retain added items.

Here is a snippet of the Javascript code:

home.js
var app1 = angular.module("HomeApp",['uiSlider','ui.bootstrap']);
app1.controller('HomeCtrl', function( $scope,$http,$q,$location,$window,$routeParams,$modal, $log, $timeout) {
$scope.homerating=[{"home_info_id":"94","avg":"3","price":"4900"},
                   {"home_info_id":"119","avg":"4","price":"200"},
                   {"home_info_id":"95","avg":"4.5","price":"500"}];
});

cellphone.js1
var app2 = angular.module("CellphoneApp",['uiSlider','ui.bootstrap']);
app2.controller('CellphoneCtrl', function( $scope,$http,$q,$location,$window,$routeParams,$modal, $log, $timeout) {
$scope.cellphonerating=[{"cellphone_info_id":"94","avg":"3.333","price":"4900"},
{"cellphone_info_id":"119","avg":"4","price":"4500"},
{"cellphone_info_id":"95","avg":"4.5","price":"5060"}];
});

car.js
var app3 = angular.module("carApp",['uiSlider','ui.bootstrap']);
app2.controller('carCtrl', function( $scope,$http,$q,$location,$window,$routeParams,$modal, $log, $timeout) {
$scope.carrating=[{"car_info_id":"94","avg":"3.333","price":"8900"},
{"car_info_id":"119","avg":"4","price":"900"},
{"car_info_id":"95","avg":"4.5","price":"2160"}];
});

The problem arises when dealing with different views:

home.html
<div ng-app="HomeApp">
    <div class="panel panel-default col-md-2 pull-left" ng-repeat="h in homerating">
        <div class="panel-body" >
            <h2>{{h.price}}</h2>
             <input  class="check_count" type="checkbox" ng-checked="IsChecked"  ng-model="home.selected"   /> Add to Estimate<br>
        </div>
    </div>    
</div>
</div>
cellphone.html
<div ng-app="CellphoneApp">
    <div class="panel panel-default col-md-2 pull-left" ng-repeat="c in cellphonerating">
        <div class="panel-body" >
            <h2>{{c.price}}</h2>
             <input  class="check_count" type="checkbox" ng-checked="IsChecked"  ng-model="cellphone.selected"   /> Add to Estimate<br>
        </div>
    </div>    
</div>
</div>
car.html
<div ng-app="carrating">
    <div class="panel panel-default col-md-2 pull-left" ng-repeat="c in carrating">
        <div class="panel-body" >
            <h2>{{c.price}}</h2>
             <input  class="check_count" type="checkbox" ng-checked="IsChecked"  ng-model="car.selected"   /> Add to Estimate<br>
        </div>
    </div>    
</div>
</div>

My main issues are:

1: Unsure about writing a combined function to push selected items and which controller to use?

2: Even if I add from the home controller, when transitioning to car.html, the page refreshes due to being different modules. How can cookies and sessions be utilized here?

Answer №1

  1. Utilize a factory to persist and share data across multiple controllers

  2. Opt for routes instead of standalone pages. Angular operates as a SPA (single page application) framework, where templates like home.html, cellphone.html, and car.html should all be route templates within the same module.

While it is possible to attach sub-modules as dependencies in a main module, consider consolidating all angular modules into one single module for simplicity:

main.js

// app module
var app = angular.module("MainApp",['uiSlider','ui.bootstrap', 'ngRoute']);

// routes
app.config(function($routeProvider) {
  $routeProvider.when('/home', {
    templateUrl: 'home.html',
    controller: 'HomeCtrl'
  })
  .when('/cellphone', {
    templateUrl: 'cellphone.html',
    controller: 'CellphoneCtrl'
  })
  .when('/car', {
    templateUrl: 'car.html',
    controller: 'carCtrl'
  })
  .otherwise({redirectTo: '/home'});
});

// home controller
app.controller('HomeCtrl', function( $scope,$http,$q,$location,$window,$routeParams,$modal, $log, $timeout) {
$scope.homerating=[{"home_info_id":"94","avg":"3","price":"4900"},
                   {"home_info_id":"119","avg":"4","price":"200"},
                   {"home_info_id":"95","avg":"4.5","price":"500"}];
});

// cell phone controller
app.controller('CellphoneCtrl', function( $scope,$http,$q,$location,$window,$routeParams,$modal, $log, $timeout) {
$scope.cellphonerating=[{"cellphone_info_id":"94","avg":"3.333","price":"4900"},
{"cellphone_info_id":"119","avg":"4","price":"4500"},
{"cellphone_info_id":"95","avg":"4.5","price":"5060"}];
});

// car controller
app.controller('carCtrl', function( $scope,$http,$q,$location,$window,$routeParams,$modal, $log, $timeout) {
$scope.carrating=[{"car_info_id":"94","avg":"3.333","price":"8900"},
{"car_info_id":"119","avg":"4","price":"900"},
{"car_info_id":"95","avg":"4.5","price":"2160"}];
});

index.html

<html ng-app="MainApp">
  <head>...</head>
  <body>

    <!-- this is where the views (home/cell/car.html) will populate -->
    <div ng-view></div>

  </body>
</html>

update

Considering your feedback, you might want to explore angular locker. It utilizes local/session storage instead of cookies, which can be advantageous. The entries seem to be namespaced by module name, so additional configuration or module renaming may be necessary. Nonetheless, it should enable your data to persist through complete page changes

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

Navigating child HTTP requests for a collection in AngularJS

Within my service.ts file, I am reading a bookmarks.json file that contains a list of bookmarks. For each bookmark, I need to set a favicon by making a call to https://www.google.com/s2/favicons?domain=... Below is the function responsible for this tas ...

Make sure to wait for the VueX value to be fully loaded before loading the component

Whenever a user attempts to directly navigate and load a component URL, a HTTP call is initiated within my Vuex actions. This call will set a value in the state once it has been resolved. I am looking to prevent my component from loading until the HTTP ca ...

"Encountering issues with logging in through AngularJS and the $http request functionality

My goal is to login using $http and GET of REST web services. This is my approach: Retrieve data based on username and password using $http.get Store the result in $scope.getResult=res; Assign variables to the retrieved data: var result=$scope.getResult ...

Modifying multiple objects with Vue's V-Model

When utilizing the mounted function in Vue to assign two different objects in the data area and bind one of them to a form, an unusual issue arises: Both objects change when input values are entered in the form For example: <template> <v-card ...

Displaying XML data using d3js

Currently, I am working on a d3.js assignment for my school project. While looking at some examples to load an XML file, I seem to be encountering difficulties in figuring out what's going wrong. The XML file is loading correctly, but as I am still le ...

Enable JSON Data Management through Express

I am utilizing the lowDB dependency to manage JSON data in conjunction with Express, and for the most part, it is functioning properly. However, I have encountered a bug that I am struggling to resolve. I have created a /create page where users can input ...

Guide to encoding data using a multidimensional array in JSON format

I have an array that looks like this: array { [0] => {"ID":"343","name":"John","money":"3000"} [1] => {"ID":"344","name":"Erik","money":"2000"} [2] => {"ID":"346","name":"Ronny","money":"3300"} } My goal is to transfer this data from ...

Is it possible to automatically adjust the text color to match the background color?

In my hypothetical scenario, I am part of a group chat where the owner has the ability to change the background color of the chat bubbles. Each user's username appears on top of their respective bubble in one of ten pre-assigned colors. However, not a ...

Deliver integers using Express.js

When I try to send a response with Express using the code below, it doesn't work: res.send(13245) An error message is displayed: express deprecated res.send(status): Use res.sendStatus(status) instead src/x.js:38:9 (node:25549) UnhandledPromise ...

Circular center button in the footer UI

Struggling with aligning a button in the footer perfectly? I have two icons on each side and while the UI is almost there, something seems off with the center icon's padding and shadow. I'm currently working with material-ui. Take a look at the i ...

PHP: Link to logo in different folder by including 'nav.php'

I am facing an issue with my nav.php file: <div> <!-- there's a lot of code here so I want to write it once and include it in all pages within the main folder as well as subfolders <img src="logo.png"> </div> The structur ...

Hide other dropdown when one dropdown is clicked

I am currently working with a dropdown data-filter in combination with the isotope plugin. My goal is to have the ability to close an open dropdown when another list item is clicked, and also have the arrow twirl down when the dropdown is open. I am seek ...

Handsontable's unique text editor feature is encountering a tricky issue with copying and pasting

In my table, there are two columns: name and code. I have developed a simple custom editor for the code column, where the user can double click on a cell to open a custom dialog with a code editor. You can view a simplified example of this functionality he ...

The table is not visible when using Bootstrap Vue

Can anyone help me with displaying a table of flowers? I am having trouble making it show up on my page. Not quite sure how to use my data to get the flowers to display properly. Any guidance or advice would be greatly appreciated. <b-table> ...

What could be causing JavaScript's wrapInner function to throw an error?

Somehow, the Firefox add-on I've been working on isn't functioning as expected. The initial line of code is executing without issues, which wraps content in a div element with an id of 'content_cont'. However, any subsequent lines of co ...

Internet Explorer causing problems with JQuery

I encountered an error with the following code snippet: jQuery.post('/user/result/generate',{ 'id': getHidden() }, function(html) { $('#result').html(html); }); The error message is: ...

"Exploring the use of AngularJS for accessing both localhost and remote

On my page, there is a button and a form. Initially, only the button is visible because the form is hidden using an ng-hide condition (link to third party website). When you click the button, you will be redirected to another page for login. Once logged in ...

Ways to verify whether a callback function supplied as a parameter in Javascript has any arguments

My task involves implementing the following: doSomething .then(success) .catch(failure); The success and failure functions are callbacks that will receive their value at runtime (I am developing a module). Therefore, I need to ensure that the fa ...

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 ...

Creating captchas seems like a mistake in reasoning to me

I am encountering an issue with my code. I created a basic newbie-level captcha using Javascript. Below is the code snippet: <!DOCTYPE html> <html> <head> <style> </style> </head> <body> <h1>T ...