Tips for eliminating redundancy in $scope manipulation code within multiple controllers using angularJS

Apologies if this question seems trivial, but I am just getting started with angularJS.

I have created two controllers: seekerController and wizardController...

Within the wizardController, there is a Scope object called chat, which is being manipulated by several functions.

Now, as I switch back to the seekerController, I realize that I need to replicate the same chat Scope object and its associated functions from the wizardController.

One way to do this would be to simply copy all the code into the other controller, but that would lead to duplication across my project...

So, I'm seeking a solution where I can centralize this logic in one place yet still access the chat Scope object and functions from both controllers seamlessly.

Update - Code Samples:

//seekerController
angular.module('cg.seeker', [])
    .controller('SeekerController', ['$scope', 'seekerService', 'timeService', 'chatService', '$stateParams', 'toastr',
      function ($scope, seekerService, timeService, chatService, $stateParams, toastr) {
        ...
        // CHAT FUNCTIONALITY
        $scope.chat = { close: true };
        chatService.unreadCount(function(count){
          $scope.chat.unreadCount = count;
          $scope.$apply();
        });
        
        // Rest of the functions for manipulating chat object...

     ...

I've replicated the above code in another controller WizardController, verbatim without modifications... and even a third controller also has some of these functionalities, though not all.

Answer №1

One step further from angularjs controllers are the:

  • Factory
  • Service
  • Provider

An example of this could be implementing a service like chatService to house common code. This service can then be injected into any controller needing that functionality, allowing for method invocation on the Service.

Note that while only the Service option was mentioned above, any of the three choices can be utilized.

UPDATE 1:

A way to streamline your code is moving shared elements from Controller to Service. For instance: Consider shifting the creation of the msg object from the controller to the chatService. The controller would then look like -

$scope.sendMsg = function (opponentId) {
      chatService.sendMsg(opponentId);
      $scope.chat.msg = '';
    }

The heavy lifting would be handled by your chatService.

    $chatService.sendMsg = function (opponentId) {
      var msg = {
        type: 'chat',
        body: $scope.chat.msg,
        extension: {
          save_to_history: 1,
        }
      };

      sendMsg(opponentId, msg);
    }

By simplifying the Controllers, you may want to reconsider if using just one controller instead of three is feasible given their similar functions.

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

Utilize jQuery to seamlessly transfer each recorded audio file from rows to corresponding input fields within the table

I have a table below with 2 rows but it can be doubled with a button (Add another Word media) and only one submit button for all rows: <tbody> <tr class="form-row dynamic-medias" id="medias-0"> <td class=&quo ...

When retrieving the card in React, only the first element is affected by the .map function

There seems to be an issue with Arrays.map as it is only working for the first object in the array. Here is the main function: function App(){ return ( <div> <NavBar /> { data.map((prop) =&g ...

Tips for increasing visibility for your Google Analytics Embed API Custom Components

I recently tried to incorporate some code I found at the following link: After downloading the files view-selector2 and date-range-selector, I saved them in my local directory. I made a modification to the code: var accountSummaries = require(['&ap ...

AngularJS - seamless navigation to url with hash symbol

Currently, I am in the process of developing a web application using a combination of AngularJS and Laravel. Everything seems to be working fine when I navigate through the URLs and links within the app. However, an issue arises when I try to directly inp ...

Phonegap enables iOS keyboard to dynamically adjust screen size during use

Currently, I am developing an iOS app using phonegap 3.0 and have encountered a particular issue. In my app, there is a window where users are required to enter a promo code. The problem arises when I click on the input area (see this example) and then pr ...

Deactivate the submit button when the form is not valid in angularjs

I am currently facing a challenge with my form that contains multiple input fields. To simplify, let's consider an example with just two inputs below. My goal is to have the submit button disabled until all required inputs are filled out. Here is wha ...

ReactJS & MobX: Unusual TypeError Occurs - Functionality Issue?

This code snippet defines the SidenavStore.js, which determines if the Sidenav should be visible or not by default: const SidenavStore = types .model('SidenavStore', { isSidenavVisible: types.optional(types.boolean, true), }) .actions( ...

Tips for choosing a specific value that matches a property value within a JSON dataset

Is there a way to select a specific value in JSON based on another property value? For example, I would like to pass the configuration_code and retrieve the corresponding description. configurations: Array(2) 0: configuration_code: "SPWG" d ...

Unveiling the approach to accessing a nested function with jQuery

While the title may be a bit misleading, I couldn't think of a better way to describe it. I've created a function that allows a small pop-up window to appear when a link is clicked (to confirm whether or not an article should be deleted). Addit ...

including a content tag into an input field within a template

I'm experimenting with the new html5 template tag to create a versatile form that can be used in various situations without relying heavily on javascript. Check out this fiddle to see what I have so far http://jsfiddle.net/684uH/ My objective is to ...

Proper techniques for storing element count in Protractor

I am a beginner when it comes to using Protractor and I am not entirely satisfied with the code snippet below, even though it is functional. My goal is to store the count in a variable (named "nb_before") and use it later on. However, due to the promi ...

Having trouble accessing portlet resource URL from JavaScript in Liferay 6.2

I have been working with Liferay Portal 6.2 CE GA3 and I am facing an issue where I need to execute a custom portlet resource method from another portlet's JSP file. Below is the code snippet I am currently using. <a href ="#" onclick="myfunctio ...

When you click on the input field, a file manager window will open. You can then select a file and the URL of the selected file will be automatically added to the

I need assistance with customizing the code to open the flmngr window and add the URL of the selected file to the input field when onclick. window.onFlmngrAndImgPenLoaded = function() { var elBtn = document.getElementById("btn"); // Style bu ...

Strikeout list on click of a mouse

Is there a way to apply strikethrough formatting to text with just a mouse click? The CSS for lists is beyond the form field margin. I've tried multiple methods without success. No matter how many times I change the code, I can't seem to get it r ...

Issues have been reported regarding the paramMap item consistently returning null when working with Angular 8 routing

I am encountering an issue with Angular 8 where I am trying to fetch some parameters or data from the route but consistently getting empty values. The component resides within a lazy-loaded module called 'message'. app-routing.module.ts: ... { ...

Tips for dynamically sending data without explicitly stating the name:

Looking to create a JSON structure with name and value pairs such as name:"john". Check out the code snippet below: var allFields = []; var inputs = document.getElementsByTagName('input'); for(var i=0; i<inputs.length;i++){ name = in ...

Surprising message found within a pug file containing javascript code

I'm encountering an issue that I am unsure how to resolve. I am relatively new to working with pug files and the error message below is appearing: Error: /home/nobin/jadeApp/views/show_message.pug:9:33 7| else 8| h3 New person, ...

Using jQuery to display items from GitHub API in a custom unordered list format

Attempting to access data from the GitHub API using jQuery (AJAX) and display it on a static webpage. Here are the HTML and JS code snippets: $(document).ready(function(){ $.ajax({ url: 'https://api.github.com/re ...

Customize date filtering in KendoUI grid

I am trying to modify the date format in the filter of my kendo grid. For example, I would like to change 1/30/2015 to Jan 30, 2015 I have successfully changed the date format for Start Date field: "StartDate", title: " ...

"Troubleshooting: NuxtJs vue-flip feature stuck on front side, not rotating to

I have recently installed the vue-flip plugin in a NuxtJs (VueJS) project that I created using the command: npx create-nuxt-app <project-name>. In the index.vue file, I simply added: <vue-flip active-click="true"> <div slot="front"> ...