Angular service to display an array of data

I have been experimenting with Angular, working on small exercises to improve my skills. I have managed to display objects in the controller but am struggling to use service and factory to display an array called "names" on a table. Can someone please review my code and point out what I am doing wrong? Additionally, how can I use a factory to achieve the same result? Here is the code:

After receiving some answers, I realized that the factory is not displaying the ethnicity information as expected.

Answer №1

To remedy your current implementation, you simply need to make two adjustments. First, update the servicee.names in your controller to servicee.names(). Then, in your template, modify s.names to just s.

If you were to achieve the same functionality using a factory, it would look like this:

myApp.factory("nameFactory",function(){
  var names= ["jay","anu","sharon","jose","mary"];

  return {
      getNames: function(){
        return names;
      }
  }
});
myApp.controller("ctrl", function($scope,nameFactory){
  $scope.person=[
     {name:"jay",age:25,salary:85000},
     {name:"anu",age:23,salary:65000},
     {name:"jose",age:26,salary:75000},
  ];

  $scope.callnames = nameFactory.getNames(); 
});

The distinction between a factory and a service lies in the fact that a factory is essentially a function that returns an object with desired values or functions, while a service is instantiated using the new operator, enabling us to expose anything by attaching it to this.

Answer №2

In order to access the functionality of the servicee, you need to call the function within your controller.

$scope.callnames = servicee.names();

Next, in your HTML code:

<tr ng-repeat="s in callnames">
     <td>{{s}}</td>
 </tr>

UPDATE: If you prefer using a factory instead of a service:

myApp.factory("myFactory",function(){

    var names= ["jay","anu","sharon","jose","mary"];
    this.names = function(){
          return names;
    }

    return this;

});

Then, in your controller, keep it consistent:

myApp.controller("ctrl", function($scope,myFactory){

    $scope.person=[

        {name:"jay",age:25,salary:85000},
        {name:"anu",age:23,salary:65000},
        {name:"jose",age:26,salary:75000},


    ];

  $scope.callnames = myFactory.names(); 


});

ANOTHER UPDATE: There is an issue with duplicate 'Asian-Indian' values in your array, to resolve this, include track by $index in your HTML.

<tr ng-repeat="e in calleth track by $index">
     <td>{{e}}</td>
</tr>

Answer №3

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

// myApp.controller("ctrl",function($scope){

// $scope.person =
// [

//        {name:"john",age:30},
//        {name:"sam",age:20},
//        {name:"jay",age:25}

//     ];

//     $scope.title = "Learning Angular"
// })
// _____________________________________________________________________________________
// _____________________________________________________________________________________
// _____________________________________________________________________________________

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

myApp.filter("agefilter", function(){

var x= function(age){
    if(age==23){

        return "Young";
    }

    if(age==25){

        return "Mature";
    }
    if(age==26){

        return "Oldest";
    }
}
return x;
});

myApp.controller("ctrl", function($scope,servicee){

    $scope.person=[

       {name:"jay",age:25,salary:85000},
        {name:"anu",age:23,salary:65000},
         {name:"jose",age:26,salary:75000},


    ];

  $scope.callnames = servicee.names(); 


});
myApp.service("servicee",function(){

      var names= ["jay","anu","sharon","jose","mary"];
this.names = function(){
      return names;
}


});
 <!DOCTYPE html>
 <html>
 <head>
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
 <title></title>
 </head>
 <body ng-app="app" ng-controller="ctrl" >


 <table border="1">
     <tr>
         <th>Name</th>
         <th>Age</th>
         <th>Salary</th>


     </tr>

     <tr ng-repeat="i in person">
         <td>{{i.name |uppercase }}</td>
         <td>{{i.age|agefilter}}</td>
         <td>{{i.salary|currency}}</td>


     </tr>



 </table> <br><br><br>


  <table border="1">
     <tr>
         <th>Name</th>



     </tr>

     <tr ng-repeat="s in callnames">
         <td>{{s}}</td>


     </tr>



 </table>


 <script src="../js/angu.js"></script>
 </body>
 </html>

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

Exploring the Art of Navigation with Ionic and Angular

Trying to integrate Angular, Meteorjs, and Ionic Framework has been a smooth process, thanks to the urigo:angular and urigo:ionic packages. However, I'm facing difficulties in configuring ionic links and angular routing to make it work seamlessly. Des ...

Bot is being inundated with messages containing no content

My discord.js version is 14.0.3. I'm facing an issue where the message content is not being retrieved correctly. To solve this, I set up a client.on('messageCreate') event handler: client.on('messageCreate', async (message) => ...

Modify the internal value of a nested array

I have a challenge where I need to update a specific value in a recursive array. The array contains the path to the variable that needs to be changed: $scopePath is the designated path for the update. For instance, if $scopePath==Array("owners","product ...

Transform Gulp task into webpack configuration

Main responsibilities: Concatenate and minify JS files in a specific order Ensure that minification does not disrupt AngularJS modules Include an MD5 string in the output JS filename to prevent browser caching, e.g. bundle-24141asd.js Update the generate ...

Exploring an Array in SwiftUI's Data Model

Help needed with a challenging SwiftUI issue! In my current project, I am facing an issue with two lists in a view that are connected to a Data Model struct. When a row is selected in the first list, I update a @State variable with the title of the select ...

Display/Modify HTML form

Looking for advice on how to create an interactive HTML form that displays data and allows users to edit it by clicking 'Edit' before submitting changes. Any suggestions on how to implement this functionality? ...

Is it possible to securely embed videos on external websites while also utilizing tokens to safeguard the content?

Protecting our video content on our website is a top priority, which is why we have implemented a system where a token is grabbed through AJAX and verified through PHP before allowing the download of any files. As I delve into providing an embed feature s ...

Sequelize: When attempting to use .get({plain: true})) method, an error is returned indicating that .get is

I'm facing a strange issue as I am able to retrieve only the values of an instance in other parts of my code without any problems. Can you spot what might be wrong with my current code? app.get('/profile', checkAuth, function(req, res) { ...

Utilizing Javascript's Mapping Functionality on Arrays

Here is an array that I need help with: var gdpData = {"CA": 1,"US": 2,"BF": 3,"DE": 4}; I am trying to retrieve the value associated with BF using a loop Can anyone provide guidance on how to accomplish this using either JQuery or Javascript? ...

typescript handling a supposedly optional property that is not truly optional

As I embark on my journey with TypeScript, please bear with me if this is not the conventional way of doing things. I have a few objectives in transitioning this JavaScript code to TypeScript. Item = {} Item.buy = function (id) {} Item.sell = function (i ...

What is the process for inserting a document into an array that is nested within another array?

My current dilemma revolves around a document (referred to as 'root') which contains an array of other documents ('stick'), each of which in turn contain another array of documents ('leaf'). Simply put: root{ stickChain[leaves ...

Concerns regarding the efficiency of JavaScript (Odin Project, Etch-a-Sketch) are arising

Currently, I am delving into Javascript on the Odin Project, tackling the Etch-a-Sketch exercise. This involves creating a board where you can draw with your cursor. As part of the exercise, there's a requirement to add a resize button that allows use ...

Is it true that using filter(x => !!x) yields the same result as filter(x => !!x && x)?

Can someone explain if filter(x => !!x) is equivalent to filter(x => !!x && x)? While both expressions seem to yield the same result, I am curious about the underlying principles behind this. ...

Can you explain the contrast between aws-amplify-react and @aws-amplify/ui-react?

I have come across multiple sources recommending the use of aws-amplify-react, but in the documentation for getting started with React, I found a different package @aws-amplify/ui-react that utilizes the module withAuthentication (which is also present in ...

manipulating elements of an array within a .map method

i am stuck with a json exporting database. it generates json data in the following format. {"Drinks":[ { "name":"name", "discription":"discription", "image":"image", "ingredients&qu ...

JavaScript for URL encoding

Hey there, I've been using the function below to encode my data and send it through the GET method. I'm utilizing AJAX for sending and PHP for receiving. function urlencode(a){ a=encodeURIComponent(a); a=a.replace(/\\/g,&apos ...

Issues with Materializecss sidenav functionality

Struggling to implement the sidenav with Materializecss. Check out the: MATERIALIZECSS SIDENAV DEMO MY CODEPEN https://codepen.io/gregoryksanders/pen/RxoyqB <head> <!--Import Google Icon Font--> <link href="https://fonts.googleap ...

``What are the steps to identify and retrieve variables from an Angular HTML template by utilizing Abstract Syntax Trees

I am currently working on a project in Angular that utilizes HTML and Typescript. My goal is to extract all the variables from the HTML templates of each component. For example, let's say I have an HTML component like this: <div *ngIf="value ...

I am facing a problem with Python selenium where I am unable to manually click on a div, but

Today is my first time using python and selenium. Learning new things is always fun :D. I managed to create a script for logging in with username and password. Successfully clicked on the button to log in. However, I encountered an issue when trying to a ...

Creating a header for an HTML table with merged columns in jQuery DataTables

Whenever I attempt to implement the jQuery DataTables plugin, it encounters an error stating c is undefined on line 256 (as seen in the minified version). The structure of my table is as follows: <table class="datatable"> <thead> ...