"Encountering problem while loading data with the ng-table function

I'm struggling to load a data set using ng-table. Could you please review my sample service and controller below?

app.service('ContactService', function () {
    var bfLosses = [ 
        { idx: 0, uid: 'User 11', name: 'Name 11', area: 'Area 1'},
        { idx: 1, uid: 'User 12', name: 'Name 12', area: 'Area 1'},
        { idx: 2, uid: 'User 21', name: 'Name 21', area: 'Area 2'},
        { idx: 3, uid: 'User 22', name: 'Name 22', area: 'Area 2'}
    ];    
}

I want to fetch the above array to populate the table in my controller.

app.controller("businessController", function ($scope,NgTableParams,ContactService){
    $scope.tableParams = new NgTableParams({
        group: "area"
      },{
        dataset:   $scope.bfLosses
    });    
});

When I define the array inside the controller, everything works fine. However, I need to access it within the controller.

Answer №1

To ensure reliable service, it is recommended to return a reference:

app.service('ContactService', function () {
    var bfLosses = [ 
        { idx: 0, uid: 'User 11', name: 'Name 11', area: 'Area 1'},
        { idx: 1, uid: 'User 12', name: 'Name 12', area: 'Area 1'},
        { idx: 2, uid: 'User 21', name: 'Name 21', area: 'Area 2'},
        { idx: 3, uid: 'User 22', name: 'Name 22', area: 'Area 2'}
      ];
    return {
      bfLosses: bfLosses 
    };
}

Make sure to access the service through the injected dependency:

app.controller("businessController", function ($scope,NgTableParams,ContactService){
    $scope.tableParams = new NgTableParams({
        group: "area"
      },{
        dataset:   ContactService.bfLosses
      });
});

Answer №2

In situations involving services, it is appropriate to use 'this' instead of using it with factories.

app.service('ContactService', function () {
this.bfLosses = [ 
    { idx: 0, uid: 'User 11', name: 'Name 11', area: 'Area 1'},
    { idx: 1, uid: 'User 12', name: 'Name 12', area: 'Area 1'},
    { idx: 2, uid: 'User 21', name: 'Name 21', area: 'Area 2'},
    { idx: 3, uid: 'User 22', name: 'Name 22', area: 'Area 2'}
  ];
});

Controller:

app.controller("businessController", function ($scope,NgTableParams,ContactService){
  $scope.tableParams = new NgTableParams({
    group: "area"
  },{
    dataset:   ContactService.bfLosses
  });
});

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

Is there a more efficient way to streamline this function?

Hey there, I'm currently working with this function: const [shopItems,setShopItems] = useState("");_ useEffect(()=> { commerce.products.list().then((product) => { setShopItems(product) }); }, []) function categori ...

I'm feeling a little lost trying to navigate my Express app. Can anyone help clarify which specific portion is considered

I'm feeling a little unsure about this, but I'm currently working on an express API app as part of a Codecademy exercise and I'm not quite sure which aspect of the app actually constitutes the API. Essentially, there's a file that cont ...

Ways to determine if the keys of an object are present in an array, filtered by the array key

Working on an Angular 2 Ionic application and I'm wondering if there's a straightforward way to filter individuals by age in a specific array and then verify if any key in another object matches the name of a person in the array, returning a bool ...

Validation within nested Joi schemas

Need help validating a nested object conditionally based on a parent value. const schema = Joi.object({ a: Joi.string(), b: Joi.object({ c: Joi.when(Joi.ref('..a'), { is: 'foo', then: Joi.number().valid(1), otherwise: Jo ...

Limiting decimal places in Angular filter

Is there a way to create a custom filter that takes an input, specifies the maximum number of decimals to display, and returns a string formatted according to locale rules? Input(number) Output for 1 decimal Output for 2 decimals 1.01 1 ...

When using Javascript's querySelector, often times it returns null

Here is the HTML code I am working with: <button class="pop-btn"> Pop </button> While I was able to style this button using CSS, I encountered a problem when trying to select it in Javascript: const Population_div_Button=document. ...

Assign the value of the selected option to the ng-model instead of the displayed text

When creating a new user, I am collecting user input. Users have the option to select their state from a dropdown menu. I am looking to save the state ID instead of the state name when the user makes a selection. How can I assign the state ID to the newSit ...

Capturing Vuejs data for various pathways

Currently, I am developing a Vue file that contains the following code: <router-link :to="{name: 'detailed'}" tag='li' @click='getData("test")'> testing</router-link> In the script section, the code looks like th ...

jQuery ajax response html not being updated in div on webpage

I have been struggling with this issue for days and I can't seem to find a solution. My goal is to update a link on a web page with a new file. Even though the post request and new file are visible in the Google Chrome development network, the actual ...

Prevent multer from uploading files if the field is left blank

Is there a way to prevent multer from attempting to upload a file if a specific field is left blank in a post request for users to update their profile? For example, if a user only wants to update their bio and not their profile picture. Here's the c ...

I'm curious about integrating Font Awesome into my React.js project - any tips on

I'm having trouble getting Font Awesome to display in my React JS project. Here is the code I am using: import React, {Component} from 'react' import './category.css' import axios from 'axios' import Course from './c ...

Error message "Webpack is encountering an issue stating you might require a suitable loader" appearing during React development using TypeScript

I've been struggling to set up a new project using webpack, react, and typescript. Despite my efforts, I can't seem to get it to work. I've experimented with the html loader and followed various tutorials to try and resolve the issue. Here ...

A step-by-step guide on including a php file with jquery

I've already clicked on this link, How to include PHP file using jQuery? However, when I try it in my code, it's not working. What could be the issue? index file <div id="content">Hi</div> <script type="text/javascript"> va ...

Error: The application encountered an issue while trying to initialize the module

Forgive me for asking, but I have searched many topics with the same name and they didn't help. It seems like everyone has their own specific code. var app = angular.module('iop', []); // Setting up the service factory to create our ...

What is the best way to change an HTML class using PHP?

I'm currently facing a challenge with my "Newsletter Subscription Form". I rely on MailChimp for sending out newsletters and have successfully set up a custom PHP file to redirect visitors after they enter their email. Here's the step-by-step pr ...

One method I use to retrieve ajax data and assign it before rendering the view

Despite putting the ajax.get in the created function, I am still unable to retrieve the ap_name value. This issue is related to vue.js created: function () { ajax.get('/envs').then(function (res) { this.apName = res.AP_NAME; ...

Map Row is unreturned

I am having trouble when attempting to map a JSON response from a MySQL query as I am receiving no response: data: NULL This is the code in question: const audience = rows.map((row) => { db.query(CountAudiences, [row.campaign], function(err, count ...

Utilizing LocalForage in conjunction with jQuery's promise library

I am currently using LocalForage for handling persistent storage in the browser and unfortunately, I have also incorporated jQuery's deferreds and promises throughout the rest of my project. I'm faced with a challenge where I need to use $.when t ...

The connection between `this` and its calling context

Is all information from its call site accessible to a function? I was under the impression that a function would have access to the scope of its call site, but I could be mistaken. Any feedback and explanation would be greatly appreciated. function bar() ...

Embedding various files onto a webpage using the file attribute

I came across some code that allowed me to add multiple files using a single input element on my page. The code can be found here: However, as someone who is new to JavaScript, I faced difficulties in customizing it to my needs. What I really want is to h ...