Unable to retrieve Angular Service variable from Controller

I am facing an issue with my Angular Service. I have set up two controllers and one service. The first controller fetches data through an AJAX call and stores it in the service. Then, the second controller tries to access this data from the service. While I have successfully passed the data from the first controller to the service, the data is not being retrieved when accessed from the second controller.

Just to clarify, I have one view that contains both controllers.

Thank you

Service

app.service('SharedDataService', function () {
  // Holds subtask that will be passed to other controllers
  // if SharedDataService is invoked.
  var _subTask = {};
  return {
    subTask : _subTask
  };
});

Controller 1

app.controller('MainCategoryController',function($scope,$http,SharedDataService){

    $scope.loadSubtask = function(m_uid){
        $http({
            method: 'POST',
            url: $locationProvider + 'query_stasks',
            data: {
                m_uid: m_uid
            }
        }).then(function successCallback(response) {
                SharedDataService.subTask = response.data;
            },function errorCallback(response){
        });

    }

}

Controller 2

app.controller('SubTaskController',function($scope,$http,$location,$rootScope,SharedDataService){



    $scope.$watch('SharedDataService.subTask', function(newValue,oldValue){
        console.log("ni sud');");
        if (newValue !== oldValue) {
            $scope.subTasks = newValue;
        }   
        return SharedDataService.subTask; 
    });

}

Answer №1

Due to SharedDataService not being part of the $scope, the first parameter in the $watch method must be a watchExpression function rather than an Angular expression string.

app.controller('SubTaskController',function($scope,$http,$location,$rootScope,SharedDataService){

    $scope.$watch(
        function watchExpression() {return SharedDataService.subTask},
        function listener (newValue,oldValue){
            console.log("ni sud");
            if (newValue !== oldValue) {
                $scope.subTasks = newValue;
            }
        }    
    });

});

For further details, visit AngularJS $rootScope.scope API Reference - $watch.

Answer №2

If you want to store values using an object in a service, consider implementing it like this in your project:

app.service('SharedDataService', function () {
  var service = {};
  service._subTask = '';
  service.toggleSubTask = function(value) {
    if (value){
        service._subTask = value;
    }
    return service._subTask;
  }
  return service;
});

Then, in your controller, utilize `service.toggleSubTask` to both set and retrieve the value. Give it a shot and best of luck!

Answer №3

It is necessary to create a method for storing data in the service and then retrieving it from the service.

   app.factory('SharedDataService', function () {
   // Holds subtask that will be passed to other controllers
   // when SharedDataService is called.
  var _subTask = [];
   function setSubTask = function(data){
    _subTask = data;
   };
   return {
   subTask : _subTask,
   setSubTask:setSubTask
   };
});

Then, in the controller, make the following call:

SharedDataService.setSubTask(response.data);

This sets the data...

Answer №4

give it a try

    app.service('SharedDataService', function () {
   this._subTask = {};
});

 // do not change the code in the 1st controller
app.controller('MainCategoryController',function($scope,$http,SharedDataService){

$scope.loadSubtask = function(m_uid){
    $http({
        method: 'POST',
        url: $locationProvider + 'query_stasks',
        data: {
            m_uid: m_uid
        }
    }).then(function successCallback(response) {
            SharedDataService._subTask = response.data;
        },function errorCallback(response){
    });

}

}

// for the 2nd controller

app.controller('SubTaskController',function($scope,$http,$location,$rootScope,SharedDataService){

console.log(SharedDataService._subTask );
});

Answer №5

It's a best practice to create $http/resource calls within services rather than directly in controllers or directives. This approach promotes modularity and reduces the dependencies between different components.

The recommended way is to define a factory like this:

app.factory('SharedDataService', function ($http) {
         var subtasks = [];
         var saveSubtasks = function(sub){
           subtasks = sub;
           console.log(subtasks)
         }
         var tasks = {
          loadSubtasks : function(m_uid){
            $http({
                      method: 'POST',
                      url: $locationProvider + 'query_stasks',
                      data: {
                          m_uid: m_uid
                      }
                }).then(function(data){
                  saveSubtasks(data);
                });
          },
          getSubtasks : function(){
            return subtasks;
            }
          }
        return tasks;
    });

You can then use this factory in your controllers like so:

app.controller('SharedDataService',function($scope,SharedDataService){
  $scope.load = function(val){
    SharedDataService.loadSubtasks(val);
  }
});

app.controller('SubTaskController',function($scope,SharedDataService){
  $scope.get = function(){
    $scope.subtasks = SharedDataService.getSubtasks();
    console.log($scope.subtasks);

  }
});

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

What is the average time frame for completing the construction of an electron project?

My project has only a few npm dependencies, but the build process is taking longer than 30 minutes and still counting. I'm not sure if this is normal or if there's an issue causing the delay. I have two specific questions: Is it common for pro ...

Transferring information from the router to the server file using Node.js and Express

I am in the process of creating a web application using node.js, and I need to transfer data from my router file, which handles form processing, to my server file responsible for emitting events to other connected users. router.js module.exports=function ...

Tips for displaying an asp.net form using javascript functions

I am currently developing a login page in asp.net and have utilized a template from CodePen at http://codepen.io/andytran/pen/PwoQgO It is my understanding that an asp.net page can only have one form tag with runat="server". However, I need to incorporate ...

How to Set Up Bower in WebStorm

I require assistance with the installation process of bower in WebStorm. My current version is 11.0.2 and I have a package.json file that needs to include bower.json for implementing a date-picker in Angular.js. To achieve this, I need to install bower. Th ...

Exclude the file and directory patterns from being watched with PM2: ignore folder

I need help with configuring pm2 to stop monitoring folders that have names like cache or tmp. I've tried multiple approaches in my app.json configuration file: {"apps": [{ "name": "BSTAT", "script": &q ...

Creating a dynamic table accordion with PHP and MySQL

I am currently working on creating an accordion table to display data retrieved from a database. I want the description data to be shown in a row below when clicking on the respective row. Despite my efforts in modifying various code snippets that I have c ...

Symfony Form Validation through Ajax Request

Seeking a way to store form data with Symfony using an Ajax call to prevent browser refreshing. Additionally, I require the ability to retrieve and display field errors in response to the Ajax call without refreshing the page. I have a Symfony form setup ...

Dividing the Controller and Service files from the app.js file

I'm trying to figure out how to import the employeeController so that I can use it in my application. Do I need to redefine the employeesApp module inside the controller file? Is there a way to import and utilize the file without having to manually co ...

One of the quirks of Angularjs is that the ng-enter animation will only be

The initial animation only occurs the first time. I am utilizing Angularjs version 1.2.22 Here is the CSS that I am using : .ng-enter { animation: bounceInUp 2s; } .ng-leave { animation: bounceOutUp 2s; } And this is the route configuration : ...

Is there a type-safe alternative to the setTimeout function that I can use?

When running my tests, I encountered an issue with the setTimeout method making them run slower than desired. I initially attempted to address this by using "any" in my code... but that led to complaints from eslint and others. Now, I have implemented a ...

What steps can be taken to avoid the duplication of color and stock values when including additional sizes?

Individual users have the ability to include additional text fields for size, color, and stocks. When adding more sizes, the data inputted for colors and stock will duplicate from the initial entry. Desired output: 1st Size : small color: red, stocks: 10 ...

Synchronize chat messages automatically with the scrolling window using AJAX technology

Original Content Scrolling Overflowed DIVs with JavaScript In my AJAX chat application, messages are displayed in a div with overflow: auto, enabling the scroll bar when the content exceeds the space. I am looking for a solution that automatically scrol ...

Converting Dynamo DB stream data into Json format

I need to convert the DDB stream message into a standard JSON format. To achieve this, I am using unmarshalleddata = aws.DynamoDB.Converter.unmarshall(result.NewImage); where result.NewImage is { carrier: { S: 'SPRING' }, partnerTransacti ...

When attempting to navigate to a controller using Express.Router and Passport, encountering an undefined error with req.url.indexOf('?')

The statement "var search = 1 + req.url.indexOf('?');" throws an error indicating that it is undefined. I am currently working on creating a login/registration page using passportjs on my angular frontend. When attempting to make a post request t ...

Having issues with closing a div tag using $.after() function

This issue can be better understood with an example: http://jsbin.com/lavonexuse The challenge here is to insert a full-width row after a specific column (identified by the class .insertion-point) when "Insert Row" is clicked. The problem I'm facing ...

Show HTML form elements on the page using jQuery or JavaScript

Is there a jQuery or JS library that can perform the following task: If the user inputs 'x' in A01, then make A01_1 visible. Otherwise, do nothing. <form id="survey"> <fieldset> <label for="A01">A01</label&g ...

"In a single line, add an item to an array based on a specified condition

I am trying to achieve something similar in JavaScript with a one-liner. Can this be done without using an if statement? // These versions add false to the array if condition = false let arr = await getArray(params).push(condition && itemToAdd); arr = awai ...

"Time" for creating a date with just the year or the month and year

I am trying to convert a date string from the format "YYYYMMDD" to a different format using moment.js. Here is the code snippet I am using: import moment from 'moment'; getDateStr(date: string, format){ return moment(date, 'YYYYMMDD&a ...

Require.js and R.js optimizer overlooks shimming configuration

I am facing an issue where R.js is not loading my shim properly, causing jQuery to load before tinyMCE which results in tiny being initialized before it has fully loaded. How can I resolve this problem? build-js.js: var requirejs = require('requirej ...

An issue occurred in React 16.14.0 where the error "ReferenceError: exports is not defined" was not properly

As the creator of the next-translate library, I have encountered a perplexing issue with an experimental version involving an error specifically related to React 16.14.0. Interestingly, upgrading React to version 17 resolves the issue, but I am hesitant to ...