How can I ensure my AngularJS Controller variable is accessible across all page contexts?

Working with AngularJS, I have a view controller where I initialize a variable called recipesData. Here is the code for the controller:

(function() {
    'use strict';

    angular
        .module('myApp')
        .controller('CookController', CookController);

    CookController.$inject = ['$document','$scope','$rootScope','$window'];

    function CookController ($document,$scope,$rootScope,$window) {

        var vm = this;

        var recipesData = load();

        var viewer, ui, building;

        $scope.load = function ()  {
           var data;
           // Create data 
           // ..........
            return data;
        };

    };

})();

I need to make my recipesData variable global as an external script relies on it being initialized.

<script src="https://myexternal/lib/js/script.js"></script>

How can I make the recipesData variable global or accessible from the script imported in the head of my document? The variable is currently initialized within my controller.

Thank you!

Answer №1

If you want to implement a solution using rootscope and service, but the most efficient way is to utilize a service. Here's an example of service code that you can tailor to fit your specific needs:

fcty.service('taskService', function() {
    var task = {};
    var addTask = function(newObj) {
        task = newObj;
    }

    var getTask = function() {
        return task;
    }
    return {
        addTask: addTask,
        getTask: getTask,
    };
});

Include taskService in your controller:

cntrl.controller('taskCreateController', function($scope, $http,taskService) {

// Add data to the service.

taskService.addTask($scope.data);

// Retrieve data from the service in any controller by using taskservice.

taskService.getTask();


}

This service can be customized to suit your requirements.

var app = angular.module('myApp', []);

app.service('recipeService', function() {
    var recipeData = {};
     var addRecipe = function(newObj) {
        recipeData = newObj;
    }

    var getRecipe = function() {
        return recipeData;
    }
 return {
        addRecipe: addRecipe,
        getRecipe: getRecipe,
    };

});


app.controller('CookController', function($scope, $http, recipeService) {

  var vm = this;
  var viewer, ui, building;

        $scope.load = function ()  {
           var data;
           // create data 
           // ..........
            recipeService.addRecipe(data);
            return data;
        };

});

I hope this example serves as a useful reference for you.

Answer №2

Here are three different approaches in AngularJS:

(Ranked by most commonly used)

  1. Implementation of service/factory, as demonstrated by @chiragsatapara
  2. Utilizing $rootScope.$emit for emitting events and $rootScope.$on for listening to them
  3. Directly working with $rootScope

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 a JavaScript npm module within a TypeScript webpack application

I am interested in incorporating the cesium-navigation JavaScript package into my project. The package can be installed via npm and node. However, my project utilizes webpack and TypeScript instead of plain JavaScript. Unfortunately, the package is not fou ...

`In NodeJS, facing a challenge with implementing a many-to-many relationship using Sequelize's

I'm in the process of setting up many-to-many relationships between roles and accesses. The `roles` table will contain a list of roles (admin, developer, etc...) and the `accesses` table will have a list of permissions (Create Project, Create Site, De ...

What materials are required in order to receive messages and information through my Contact page?

Currently, I am pondering the optimal method for gathering information from my Contact page. I have already created a form; however, I'm unsure how to send the gathered data to myself since I am relatively new to Web development. Angular is the framew ...

Leveraging underscore.js for null verification

let name = "someName"; if(name !== null) { // perform some action } Currently, I am utilizing http://underscorejs.org/#isNull. How can I achieve the same functionality using underscore.js? Is there any noticeable performance enhance ...

Having trouble integrating select2 with geonames?

I'm currently experiencing difficulties when trying to integrate select2 with geonames. Although I am able to generate a list of cities, I am unable to select any as a valid option. HTML <select id="cities" name= "cities"> <option value=" ...

Incorporate the Google Maps API into a React application

I've recently started learning react and I'm currently trying to integrate the Google Maps API into my React application. Within my app, I have a search input field and a designated area for the map located at http://localhost:8080/. My main qu ...

Utilizing the power of Node.js with Oracle seamlessly, without the need for the Oracle Instant

Currently, I am working on testing the connectivity to our Oracle databases. Recently, I came across node-oracledb, a tool released by Oracle that aims to simplify this process. However, one major hurdle is the requirement of having the Oracle Instant Clie ...

Tips for triggering jquery code when a variable containing a CSS attribute is modified

I have a specific requirement where I need to reset the scrollleft value to 0 on my wrapper whenever a particular CSS property changes. Although I am new to using jQuery and haven't worked with variables much, I believe I need to create a variable to ...

Move content off the screen using CSS3 translation

Throughout various projects, I have encountered the need to make elements on a webpage translate out of view (essentially making them fly out of the document). The idea was that by simply adding a class to the element, the CSS would take care of the animat ...

Using Phonegap alongside ons-scroller and ons-button

Recently, I have been using Phonegap with the Onsen UI system on iOS devices. I encountered an issue where buttons included within an ons-scroller were not clickable when running on an iPad or iPhone. Here is the code snippet that caused the problem: < ...

Using destructuring assignment in a while loop is not functional

[a,b] = [b, a+b] is ineffective here as a and b are always set to 0 and 1. However, using a temporary variable to swap the values does work. function fibonacciSequence() { let [a, b, arr] = [0, 1, []] while (a <= 255) { arr.concat(a) [a, ...

What is the best way to implement two events in onPress using React Native?

I'm trying to implement the UploadB function and toggle the modal visibility using setModalVisible(!modalVisible)... However, my attempts so far have not been successful. const UploadB = useCallback(() => { dispatch({ type: ADD_P ...

What steps can I take to incorporate a user-controlled autoscroll feature into this Carousel?

I am in the process of creating a "slideshow" using text boxes that can be scrolled with arrow buttons. My goal is to have the slideshow automatically scroll only until the user interacts by clicking one of the arrow buttons. Below is the state logic re ...

Tips for choosing an option from a dropdown menu with robot framework

Looking for guidance on how to properly select an order number from a dropdown list. On the page, there are two more dropdowns with the same repeated elements. When attempting to select text, it ends up choosing matching text from other dropdowns as well. ...

How can we ensure that Ajax consistently provides useful and positive outcomes?

Here is my PHP code: function MailList() { $this->Form['email'] = $_POST["email"]; $index = $this->mgr->getMailList($_POST["email"]); } // SQL code function getMailList($email) { $mailArray = Array(); $sql ...

One might encounter undefined JSON keys when attempting to access them from a script tag

During my attempts to load a specific Json using an Ajax GET request and then parsing it, I encountered an issue when trying to access the Json key from an HTML script tag, as it returned as undefined. To troubleshoot this problem, I decided to log all th ...

Guide on adding data from Express.js and Node.js to a database

I'm dealing with a code that involves image uploads and handling input text. I am facing an issue in inserting these values into the mysql database. The problem arises when trying to insert multiple values into the database; however, I can successfull ...

Why does `npm init react-app` automatically select yarn as the default package manager? (npm version 6.14.5)

After executing the command npm init react-app, I noticed that npm automatically selects yarn as the default package manager for the newly created app. To resolve this, I followed the steps provided in How Do I Uninstall Yarn to remove yarn from my system. ...

Customizing the jQuery Datepicker to only allow a predefined set of dates

I am looking for assistance regarding the jQuery datepicker. I have an array of dates and I need to disable all dates except for the ones in this specific array. Currently, the code I have does the opposite of what I need. I generate the array of dates in ...

Combining Django with the powerful Vue3 and lightning fast Vite

I'm in the process of upgrading my multipage app from Vue2 with webpack to Vue3 with Vite. After successfully rendering my Vue3 components on my Django templates, I am now facing a challenge - setting component variables on the Vue app using the Djan ...