The AngularJS factory and controller code seem to be failing to generate any output

After running the code below, I noticed that nothing is being displayed in my console to indicate any errors. However, in listService, there is an alert within the results, but it shows as "undefined."

My main goal is to have a repeat function that lists all Organizations on the view. Any assistance would be greatly appreciated!

Below is my factory:

app.factory("listService", ["$rootScope", "$http", "$location", "$routeParams",
    function($rootScope, $http, $location, $routeParams) {
        var siteURL = "jdfyhgyjdfghyjdgfyhkjyhjk";
        var svc = {};
        var data = null;

        svc.getListItems = function(listName) {
            $http({
                url: siteURL + "/_api/web/lists/GetByTitle('" + listName + "')/items",
                method: "GET",
                async: false,
                headers: {
                    "Accept": "application/json;odata=verbose",
                    "X-RequestDigest": jQuery("#__REQUESTDIGEST").val()
                },
                success: function(response, status, headers, config) {
                    data = response.data.d.results;
                    alert(data);
                },
                error: function(response, status, headers, config) {
                    $rootScope.error = status;
                }
            });
        }
        return svc;
    }
]);

Here is my controller:

app.controller("readOrganizationsCtrl", ["$scope", "$http", "$location", "$routeParams", "listService",
    function($scope, $http, $location, $routeParams, listService) {
        $scope.organizations = listService.getListItems('Organizations');
    }
]);

And finally, here is my view:

<div class="form-group">
    <input type="text" class="form-control" id="search" placeholder="Search organizations" data-ng-model="search" />
</div>
<table class="table table-stripped table-hover">
    <thead>
        <tr>
            <th>Title</th>
        </tr>
    </thead>
    <tbody>
        <tr data-ng-repeat="organization in organizations | filter:search" data-ng-click="editOrganization($index)">
            <td>{{organization.Title}}</td>
        </tr>
    </tbody>
</table>
<div class="form-group">
    <button data-ng-click="addOrganization()" class="btn btn-primary">Add Organization</button>
</div>
{{"Error:" + error}}

Answer №1

When utilizing $http in a controller, you can retrieve all your organizations from siteURL effortlessly with the following functional code: JS:

 var app = angular.module('plunker', []);

    app.controller('MainCtrl', function($scope, $http) {
            $http({
                method: 'GET',
                url: 'organizations.json',
                headers: {
                 withCredentials: true,
                 headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                 },
                })
                .then(function successCallback(data) {
                    $scope.organizations = data.data;
                    console.log($scope.organizations)

                }, function errorCallback(response) {
                    console.log(response);
                    console.log('error');
                });    
    });

HTML:

 <tbody>
        <tr data-ng-repeat="organization in organizations | filter:search" data-ng-click="editOrganization($index)">
            <td>{{organization.name}}</td>
        </tr>
    </tbody>

Plunker Demo: http://plnkr.co/edit/aP7fLU1tfWwmZdCAYzIf?p=preview

If you prefer to use a factory instead, you can follow this approach:

app.controller('MainCtrl', function($scope, $http, factory) {

      factory.getOrganizations()
         .then(function(data){
            $scope.organizations = data.data;
                    console.log($scope.organizations)
         })
         .catch(function(){
         })
      });

app.factory('factory',function($http){
  return {
     getOrganizations: function(){
        return $http.get('organizations.json');
     }
  };
})

Plunker Demo using Factory: http://plnkr.co/edit/UJUrTIGHGtjjccGAnHlk?p=preview

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 node sends a request to the API to retrieve data, which is then stored in an array. Subsequently, another request is

var UfcAPI = require('ufc-api'); var ufc = new UfcAPI({ version: '3' }); const fighterIdList = []; function fetchFighterIds() { ufc.fighters(function(err, res) { for (let i = 0; i < res.body.length; i++) { ...

``Creating apertures in a rectangular shape using three.js: A step-by-step guide

I've been attempting to create two holes in a simple rectangle using three.js, but I'm facing an issue where the holes aren't showing up correctly with a 3D effect. Below is my current approach: const modelContainer = document.getElementByI ...

Unable to detect the click event on Bootstrap accordion

I am currently utilizing Bootstrap to populate a table with data and then attempting to capture an accordion show event. My intention is to extract the div id in order to make an ajax call for more information on the respective item. Unfortunately, I have ...

Ensure the browser only reloads a single file

In the midst of my project, I realized that the CSS and JS files are being loaded separately onto the webpage with query strings like .css?1234 to ensure the browsers refresh the files on load. However, upon returning to the project, I discovered that one ...

Currently leveraging the TSL Mastodon API, I developed a basic function designed to extract images from a specified URL and post them on Mastodon. However, the outcomes I am receiving are not

This is the code block responsible for grabbing and uploading the image async MediaUpload(photos : any[]) { const client = await this.Login() const full_photo_urls : string[] = photos.map((item) => item.full) let image_ids : string[] = [ ...

What is the best way to bind the value of total when working with forms and the bind method?

I am working on a form where I need to pass the value of total. Regarding the total: I have successfully passed the value of the cart, which is an array. const [total, setTotal] = useState<number | undefined>(undefined); const calculateTotal = () ...

Trouble obtaining dates and values in JSON while analyzing Commodity Data Charts

{ "data": { "success": true, "timeseries": true, "start_date": "2022-02-01", "end_date": "2022-03-02", "base": "RUB", "rates": { ...

Flex just can't seem to align correctly

I'm having trouble getting this to work properly. I am using React and styled components, but the justify/content alignment is not functioning as expected. The setup includes a div with flex properties, where the flex direction is set to column. With ...

Display three bootstrap cards in each row using a template loop

How can I display my cards vertically one by one as shown below? https://i.sstatic.net/5bsS2.png The current code I have lists the cards horizontally. How can I modify it to list them vertically? {% extends 'base_content.html' %} {% block conte ...

Package for validating forms in Meteor using React

Looking for recommendations on a Meteor React form validation package or custom validation code that's compatible with components. Need something similar to jQuery validate, but specifically designed to work seamlessly with Meteor and React. ...

Issue with Yup and Formik not validating checkboxes as expected

I'm struggling to figure out why the validation isn't functioning as expected: export default function Check() { const label = { inputProps: { "aria-label": "termsOfService" } }; const formSchema = yup.object().shape({ ...

Tips for sending a prompt within a .js document

Within my script.js file, I have a prompt that collects user input (specifically a username), stores it in an array, and then should send that array to the server. I'm struggling with getting the "prompt.submit" section to function properly. Whenever ...

Concealing information beneath a veil of darkness

I'm looking to implement a solution using JS/CSS/HTML5 to hide content within a div container with a shadow effect. The end result should resemble the example image I've provided. Additionally, I'd like the ability to customize the color of ...

The datepicker fails to show the selected date in the text box following an ajax request

I have a div with the ID of inPatientDecision. The contents of this div are loaded dynamically through an Ajax call. Within the loaded content, there are HTML datepicker elements with the class attribute set to datePicker. In order to initialize the jQuery ...

Tips for applying styles to elements that are not directly related when the parent element has a specific class using CSS

I have some HTML code structured as shown below. <div class='A'> <div class='B' /> <div class='C' /> </div class='A'> <div class='D' /> My Objective: If A contains C: ...

The keyboard fails to open when trying to input text on a WKWebView

Is there a way to programmatically open the keyboard in a WkWebView for tel text input after a JavaScript function call? I want the keyboard to display for efficiency reasons when a certain input is activated, but it doesn't gain focus automatically. ...

How can data be transferred between web pages using jQuery or JavaScript?

Imagine having two different pages on a Classified car website: The first page is the search page, which displays a list of all cars. Check out a sample search page here The second page is the details page, where you can find specific information about a ...

What are some ways to enhance the functionality of the initComplete feature in Dat

$('#example').dataTable( { "initComplete": function(settings, json) { alert( 'DataTables has finished its initialisation.' ); } } ); Is there a way to extend the initComplete function for other languages? $.extend( true, $.f ...

Issue of Modal not hiding persists despite attempted solutions using JS, jQuery, and CSS

I am attempting to display a modal exclusively on mobile devices. Despite my confidence in the correctness of my JavaScript, it is not functioning as expected. Would anyone be willing to review and provide assistance? <div class="col-5 col-sm-2 ml-au ...

Adding a bootstrap label on the corner of a div using overlay technique

I'm attempting to superimpose a bootstrap label in the corner of a DIV. My goal is to position the label in the top left corner of the div, partially overlapping it. Thank you <div class="span4" style="border-bottom: none; border-top: 4px s ...