Transferring the $scope variable from Controller to Service

As I am currently developing a prototype app using Ionic, I find myself diving into the world of Ionic and Angular. In my project, I have created a small JSON API that contains around 25 objects. I have successfully displayed these objects in a list on a page named "Library". Now, my goal is to turn each item in the list into a link that will lead to an individual page called "Lesson". However, I am encountering an issue where the variable $scope.lessonId is set properly in the controller but shows up as undefined in the service. I'm wondering if it's possible to achieve what I am aiming for or if I need to rethink my approach entirely.

.controller('LibraryLessonCtrl', function($scope, $stateParams, LessonService) {
    $scope.lessonId = $stateParams.libraryId;
    console.log($scope.lessonId);

    LessonService.getLessonId()
       .then(function(response){
       $scope.lesson = response;

       console.log($scope.lesson);
  });
})

.service ('LessonService', function($http){
    return { getLessonId: function() {
        return $http.get('api/postsAPI.json')
            .then(function (response, lessonId) {

                console.log(lessonId);

                for(i=0;i<response.data.length;i++){
                    if(response.data[i].post_id == lessonId){
                        return response.data[i];
                    }
                }
            });
        }
    };
})

Answer №1

In order to utilize the value inside your service, you must pass your $scope.lessonId variable to your service call.

.controller('LibraryLessonCtrl', function($scope, $stateParams, LessonService) {
   $scope.lessonId = $stateParams.libraryId;
   console.log($scope.lessonId);

   LessonService.getLessonId($scope.lessonId)
      .then(function(response){
        $scope.lesson = response;
        console.log($scope.lesson);
   });
}).service ('LessonService', function($http){
return { getLessonId: function(lessonId) {
    return $http.get('api/postsAPI.json')
        .then(function (response) {

            console.log(lessonId);

            for(i=0;i<response.data.length;i++){
                if(response.data[i].post_id == lessonId){
                    return response.data[i];
                }
            }
        });
    }
};

})

Answer №2

To achieve this, you can pass the Id to the service and store it there instead of relying on $scope variables. It is recommended not to pass $scope variables to services for better code organization. Here's an example implementation:

 .service ('LessonService', function($http){
    var lessonId;
    return { 
        /*other methods*/
        setLessonId: function(id) {
            lessonId = id;
        },
        getLessonId: function(){
          return lessonId;
        }

    };
})

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

The variable that is extracted from a JSON object within an array successfully logs to the console inside a loop. However, when attempting to use the same variable for summation

I have a looping task where I need to add the values of certain objects together in an array. While I can successfully log the values individually, like this: console.log(workouts[0].exercises[0].break); When I try to incorporate them into a loop, I enco ...

Prevent form submission using jQuery based on ajax response, or allow it to submit otherwise

After setting up some jQuery code to handle form submission, the functionality is working well when certain conditions are met. However, I am facing a challenge in allowing the form to be submitted if the response received does not match specific criteria. ...

difficulty encountered while attempting to generate a horizontal bar chart with stacked bars using Chart.js

Struggling to create a stacked horizontal bar chart using the code below. Although the chart appears horizontally, it is not stacked as expected. I have tried looking for solutions on various platforms without success. If anyone can help identify the issue ...

Encountering a POST response error following a collection.insert operation using the NodeJS Mongo module

I encountered an error while attempting to make a POST request > process.nextTick(function() { throw err; }); > ^ > > TypeError: first argument must be a string or Buffer > at S ...

Deleting a user in Vue.js using Firebase UID

I'm working on implementing a function in my Vue.js Firebase application that allows users to be deleted by UID. The app is designed to allow user registration through email and password authentication in Firebase. Once a user is logged in, they shoul ...

What is the best way to add a dynamic Angular parameter to a URL?

Currently, my project involves working with typescript and angularjs. One of the tasks at hand is inserting a dynamic link into the code, similar to this example: http://..../Detail.aspx?code={{MyCode}} The parameter 'MyCode' is subject to chan ...

Error: The JavaScript SRC cheat is malfunctioning

Having an issue with the code below. The 'dummy1' and 'dummy2' variables are not loading their content as expected on the page. Any suggestions? <html> <head> <title>JavaScript On-line Test</title> <script LA ...

Error 9 in Firebase: The function 'initializeApp' could not be located within the 'firebase/app' module

Since updating to firebase 9, I've been encountering issues with importing certain functions that were working fine on firebase 8. I've gone through the documentation and made necessary code improvements, but the error persists. This issue is not ...

Ways to manage drag and drop functionality within Cypress when traditional Cypress techniques are not effective

I need help with the drag and drop function in Cypress. I have tried three different methods but none of them seem to work. I have included my code below, which is not functioning as expected. Does anyone have any suggestions on what might work better in t ...

Is a Page Refresh Required to Reload Routes in ReactJS?

I have created menu links labeled Home, About, What I Do, and Experience for my portfolio site using BrowserRouter. However, when I click on these links, the components do not load properly on the page; they only render correctly after a page refresh. This ...

Bringing json files from a directory into mongoDB

My current challenge involves managing a directory structure that consists of multiple sub-directories, containing approximately one million JSON files. I am looking to import all of this data into mongoDB, but have been unable to locate any helpful tutori ...

Error in Adding Items to React To-Do List

As I work on creating a React todo app following a tutorial, I have encountered an issue. Despite having components and context files set up, the addItem function does not render the item and date into the todo list when the 'Add todo' button is ...

Ordering a list in Angularjs causes ng-click to malfunction

I developed a custom jQuery plugin that enables users to reorganize a ul list using touch or mouse, similar to the functionality demonstrated here. While the plugin successfully updates the DOM, I am facing challenges informing Angular to refresh the model ...

Utilizing React Router Dom to display a specific component exclusively on certain routes

I am encountering an issue with my React application that uses React Router Dom version 6. I am attempting to display the Nav component only when the path does not match the root "/", but I am struggling to make it work properly. Below is the code snippet ...

Storing common controller functions in services for easy access within a contained scope

I am facing an issue with my Angular UI modal, as it seems to create its own isolated scope even when I try to use a method on it from the controller that wraps my application (metaCtrl). To solve this problem, I decided to store the function in a service ...

Utilizing jQuery to modify the text output from an input form

Check out the preview site at . It's a test version before launching on a separate domain. Hello, I need to customize the error response for a CRM contact form integrated into Wordpress with the help of StackOverflow. The form is connected via JavaSc ...

What is the best way to associate multiple references to a model within a nested document?

I am facing a challenge with populating a large nested document. var PortfolioSchema = new Schema({ bonds : { percentage : Number, USA : { percentage : Number, ...

It seems that the Bootstrap 4 Modal Pop up window is having difficulty closing

I recently completed a project on creating a matching game. After all the cards are successfully matched and the game finishes, a congratulatory modal pops up. However, I encountered an issue where the modal would not close after clicking the "Play Again" ...

Troubleshooting VueJs and vue-i18n issues

Currently, I am utilizing the Webpack CLI Template. As a next step, I proceed to install using the command npm install --save vue-i18n Within my main.js file, I undertake the necessary importation and configuration by setting the locale to "en" import ...

Use javascript to implement pinch zoom functionality in a canvas element by allowing users to zoom from the

Can I zoom in from the point where I pinch instead of the center of the image within a Canvas element? Here is an example of what I am looking for, but I need the same effect within a canvas. When I zoom in, I want it to be centered on the point where I z ...