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

How can I retrieve data from local storage based on a specific key value using a query?

In order to optimize the storage of data for my app, I have successfully stored a large amount in local storage. Now, I am faced with the task of fetching data in an array but only selecting key/values that are specifically chosen, rather than all or jus ...

What is the process for invoking a function in ng-repeat after an object has been altered?

I am facing an issue with the following code snippet: <ul class="list-group" ng-init="curMarks=getTaskVotesModalInfo(task)"> <li ng-repeat="info in curMarks" class="list-group-item"> <span>{{info.worker}}</span> <span ...

Design your very own personalized Show Layout component

Currently, I'm in the process of creating a unique layout component to enhance the design of my Show page. I've encountered some inconsistencies with functionality, and my solution involves utilizing the Material-UI <Grid> component. While ...

AngularJS consistently shows only one piece of data when used in conjunction with PHP

My AngularJS script below is currently only displaying one record at a time, replacing the previously submitted data. I would like it to display each submitted record individually. I suspect the issue may be related to the data call. I need it to show all ...

What is the best way to send the value from a textbox to this script?

My challenge is with this particular textbox: <input type="text" autocomplete="off" required="required" id="bar" name="bar" class="form-control" placeholder="Barcode"> Also, there's a button in the mix: <button type="button" style="float:r ...

How can the front design of Material-UI's Card header be customized?

Currently, I am facing an issue with the Material-UI card header as the background color is affecting the readability of the default font. My aim is to use the typography prop h4 for the header, but I am struggling to achieve this. https://i.stack.imgur.c ...

The absence of jasmine-node assertions in promises goes unnoticed

Everything seems to be running smoothly with the code below, except for the assertion part. Whenever I run the test using Jasmine, it reports 0 assertions. Is there a way to include my assertions within promises so they are recognized? it("should open sav ...

Unexpected behavior in the AngularJS UI Bootstrap datepicker causing dates to shift

Hi there, I have encountered an issue with setting the default date format (YYYY-MM-DD) in the UI Bootstrap datepicker input field using momentjs. Everything seems to display correctly until I try to console log the selected date. It appears that an additi ...

Ways to verify if a variable holds a JSON object or a string

Is it possible to determine whether the data in a variable is a string or a JSON object? var json_string = '{ "key": 1, "key2": "2" }'; var json_string = { "key": 1, "key2": "2" }; var json_string = "{ 'key': 1, 'key2', 2 } ...

Sending parameter and ng-click to the angular directive

I am looking for a way to transfer data from HTML to the directive, allowing the directive to be clickable using ng-click. How can I pass the parameter of the link function to the template? app.directive("hello", function(){ return { restrict: "E" ...

Best resolutions and formats for Nativescript-Vue application icons

I'm a newbie when it comes to Nativescript, and I'm looking to change the icon for my app. After doing some research, I found this command: tns resources generate splashes <path to image> [--background <color>] This command seems li ...

MUI version 5 - Checkboxes are receiving a variety of unique classes

After recently upgrading from Mui v4 to v5, I've noticed a strange behavior with checkboxes. Upon inspecting the DOM differences between the two versions, it appears that some additional classes are now being applied in v5 and the extra span with the ...

Having trouble connecting to JSTL in my JavaScript file

Currently, I am facing an issue with my JSTL code that is housed within a JavaScript file being included in my JSP page. The problem arises when I place the JSTL code inside a script within the JSP page - it works perfectly fine. However, if I move the s ...

Remove hidden data upon moving cursor over table rows after a delay

Hey there! I'm in need of a little assistance, so I hope you can lend me a hand. Here's the scenario: Within my category table, there are numerous rows, each containing a hidden textbox with an empty value and a unique ID. As users navigate t ...

Nested tables in Datatables retrieving child table rows based on parent table

I have been struggling for the past three days to get my nested Datatables working properly. I have a parent table called MAINtable and a child table called adjlinesTable. The issue I am facing is that all lines from the adjlinesTable are being drawn to ...

Changing date and time into milliseconds within AngularJS

Today's date is: var timeFormat = 'dd MMM, yyyy hh:mm:ss a'; var todayDate = dateFormat(new Date(), timeFormat); Can we convert today's date to milliseconds using AngularJS? Alternatively, how can we use the JavaScript function getT ...

How can the button effect be disabled in Vue Material for md-button?

Is there any documentation available for disabling the effect from md-button in Vue Material? Thank you ...

Retrieve an item from MongoDB and assign it to the $scope variable

Attempting to extract the product identifier from the URL (e.g. /product/<productId>), retrieve the Product object from mongodb, and make it accessible in the application's $scope. The productId extraction from the URL is successful using $route ...

I experienced an issue with Firestore where updating just one data field in a document caused all the other data to be wiped out and replaced with empty Strings

When updating data in my Firestore document, I find myself inputting each individual piece of data. If I try to edit the tag number, it ends up overwriting the contract number with an empty string, and vice versa. This issue seems to stem from the way th ...

I am looking to host several iterations of jQuery on a content delivery network within my Nuxt application

Currently, we are loading jQuery 3.1.4 externally from a CDN on the top page. index.vue head: { bodyAttrs: { id: 'overview' }, script: [ { src: 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min ...