Issues with the functionality of Angular JS services

Hey everyone, I'm relatively new to AngularJS and running into some issues with services. I've been working on a TO DO app in AngularJS using services but I just can't seem to get it to work correctly. Here is my controller:

.controller("myController", ['$scope','toDoService', function($scope,toDoService){

    var lists = toDoService.getLists();
    $scope.lists = lists;

    $scope.add = function(){
      // Any suggestions on what should be added here?

    }

And this is my service:

.service('toDoService', function(){
      this.getLists =function(){
          var list = [
              {"name" : "abebe" ,"done":false, id: Date.now()}
          ];
          return list;
      }


      this.add = function(){
         $scope.lists.push({'name':$scope.nameSpace,'done':false, id: Date.now()});
      $scope.nameSpace = '';
         return this;
      }

  });

Thank you all in advance!

Answer №1

It is not recommended to utilize $scope within a service.

Check out this helpful answer:

Answer №2

Avoid using $scope within a service. Refer to the example in this Fiddle for guidance on proper implementation.

myApp.service('toDoService', function(){
            this.details = {
        lists: [
              {"name" : "abebe" ,"done":false, id: Date.now()}
          ]
      }
      this.getLists =function(){
          var list = [
              {"name" : "abebe" ,"done":false, id: Date.now()}
          ];
          return list;
      }
      this.addList = function(item) {
        this.details.lists.push(item)
      }
  });

myApp.controller("myController", ['$scope','toDoService',       
    function($scope,toDoService){
    $scope.lists = function() { return toDoService.details.lists };
    $scope.add = function(){
      // WHAT TO PUT HERE????
      var newListItem = {"name" : "abebe" ,"done":false, id: Date.now()}
      toDoService.addList(newListItem)
    }
}]);

Answer №3

Here is the full code snippet:

.controller("myController", ['$scope','toDoService', function($scope,toDoService){

var tasks = toDoService.getTasks();
$scope.tasks = tasks;

$scope.addTask = function(){
    toDoService.addNewTask($scope.tasks);

}

The structure of your service should resemble the following:

.service('toDoService', function(){

    this.tasks = [];

    this.getTasks =function(){
        var taskList = [
            {"taskName": "do dishes" ,"completed": false, id: Date.now()}
        ];
        return taskList;
    }


    this.addNewTask = function(data){
        tasks.push(data);
        return tasks;
    }

});

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 about mixing up your backgrounds with an overlay effect for a unique look?

Hey there, I'm currently working on adding random backgrounds to my website through an overlay, but I've hit a roadblock when it comes to displaying them. Here is the code I'm working with: .css / .php #intro { background: ...

Custom calendar control vanishes on postback in ASP

After creating a custom calendar control that works smoothly for the most part, I encountered an issue. Whenever it is posted, the control disappears even when the user is still hovering over it. I want users to be able to change months, dates, or anythi ...

Obtain the content window using angularJS

I've been attempting to retrieve the content window of an iframe element. My approach in JQuery has been as follows: $('#loginframe')[0].contentWindow However, since I can't use JQuery in Angular, I've been trying to achieve thi ...

Retrieving URL from AJAX Request in Express JS

Currently, I am in the process of developing an Express App and encountering a challenge regarding the storage of the user's URL from which their AJAX request originated. In simpler terms, when a website, such as www.example.com, sends an HTTP request ...

Implementing a Timer on a Bootstrap Progress Bar Using JavaScript

I am currently working on a timer with a progress bar. The timer itself is functioning properly, but I am facing an issue with syncing the progress bar with the timer. I am utilizing the bootstrap progress bar for this project. If I remove the 'bar&ap ...

Customizing Static Templates with AngularJS Compilation

I've created a template included in a view that is stored in the $templateCache. <script type="text/ng-template" id="ratesPopover"> <table class="rate-table"> <tr ng-repeat="rate in plan.rates"> <td>Rat ...

Top method to incorporate status verification with javascript

I need to create a system where I can monitor a specific request status from the server side. What is the most efficient method to achieve this without repeatedly sending ajax requests at predefined intervals? One idea I have is to send an ajax request to ...

Data saved in AngularJS local storage disappears when a new page is uploaded

I have been working on a page containing FAQs, utilizing angular localstorage for data storage. After uploading all the files to a server for sharing, I noticed that the data gets lost and then reappears. The initial upload erases the data since it is my f ...

How can I retrieve text that is enclosed within 2 specific tags and then format the output according to my preference?

Is it possible to extract text between specific tags and format the output as desired? Are there any tools or scripts available for this task? For instance: [b]1.[/b] [artist]Norman Bass[/artist] – How U Like Bass? (Warp Brothers Club Mix) [i](3:26 ...

Encountering a syntax error with the spread operator while attempting to deploy on Heroku

I'm encountering an error when attempting to deploy my app on Heroku: remote: SyntaxError: src/resolvers/Mutation.js: Unexpected token (21:16) remote: 19 | const user = await prisma.mutation.createUser({ remote: 20 | data: { r ...

What is the process for adding two separate animations to one div using CSS?

I have created a simple example where I aim to display the output of a JavaScript function on an HTML page. Furthermore, I want to apply two different animations using CSS to this output. When attempting to apply the animations (clockwise and countercloc ...

Incorporating a React component into a vanilla JavaScript document

Currently, I am working on implementing a weather widget using an npm module called . This particular module is based on React components, which is a new territory for me. I have managed to include the CDNs provided by the npm module, but I am struggling ...

I am continuously encountering the error message "Resource loading failed" whenever I attempt to launch a React application

I'm currently developing a React App using Webstorm as my IDE. Everything seems to be configured correctly, but whenever I attempt to run the app, I encounter an error message stating "Failed to load resource: the server responded with a status of 404 ...

Enhancing user interfaces with jQuery by updating DOM elements

Can anyone help me figure out how to update a webpage so it functions as a report that multiple people can contribute to? I'm using forms to collect data and want it to instantly display under the correct category headings. Currently, I'm using j ...

What is the method for including a local copy of a globally installed NPM package?

Is there a method to have NPM install my global packages directly to a specific project? I am fond of the concept of globally installing NPM packages because it allows me to easily transfer them to my local project in case I am offline. Here's what I ...

What methods can be used to conceal a div when the content is not being shown?

I'm a beginner in HTML and CSS and I have a page with the following code: Content displayed : <div id="row-3" ><!-- Row 3 starts here --> <div class="groupz_column1" style="margin-right:0px;"><a href="http://www.xyz.in/ads/ ...

Issue encountered when attempting to retrieve dimensions of a div element

Using Vue and facing an issue with a div setup that I have: <div :style="'width:' + imageSize.width + 'px; height:' + imageSize.height + 'px'" id="image-container"></div> The dimensions are sto ...

Issue: "A 'reflect-metadata shim is needed' error occurs during the transition to Webpack 2"

My team and I are facing a challenge as we try to upgrade our code base to Webpack 2. Currently, we're encountering two stubborn errors: 'Uncaught reflect-metadata shim is required when using class decorators' and 'Cannot read property ...

To close the Muix DateTimePicker, simply hit the Escape key or click anywhere outside of the picker

I'd like the DateTimePicker to only close when the user presses the action buttons, not when they click outside or press Escape. Unfortunately, I haven't found any props to control this behavior yet. <DesktopDatePicker closeOnSelect={false} s ...

eliminate empty lines from csv files during the uploading process in Angular

I have implemented a csv-reader directive that allows users to upload a CSV file. However, I have noticed an issue when uploading a file with spaces between words, resulting in blank lines being displayed. Here is an example: var reader = new FileReader ...