Is your Angular Controller getting stuck and failing to complete its tasks

It seems like I'm missing a key component here, as I keep encountering similar issues. There must be a fundamental gap in my understanding of Angular.

The scenario involves a controller:

angular.module('NextShift')
.controller('ContactsCtrl', ['$scope','contactFactory',
    function($scope, $rootScope, Auth, $localStorage, $stateParams, contactFactory) {
       console.log("I reach this point");
       function getContacts() {
        contactFactory.getContacts()
            .success(function(contactList) {
                console.log("Why am I not reaching this point?");
                $scope.contacts = contactList;
            })
            .error(function(error){
                console.log("Or here?");
                $rootScope.error = "Failed to get contacts";
            });
    }
}
]);

Despite everything seeming to run smoothly without any apparent errors, my template remains empty and the console logs are void of any messages. My confusion deepens.

This is where my contactFactory comes into play:

angular.module('NextShift').factory('contactFactory', ['$http', function($http) {
var url = 'http://myurl.example/api/v1';
var contactFactory = {};

contactFactory.getContacts = function () {
    return $http.get(url + '/contacts');
};

contactFactory.getContact = function(id) {
    return $http.get(url + '/contacts/' + id);
}

contactFactory.updateContact = function(contact){
    return $http.put(url + '/contacts/' + id, contact);
}

contactFactory.deleteContact = function(id) {
    return $http.delete(url + '/contacts/' + id);
}

return contactFactory;
}]);

Something isn't clicking here. The console.log lines should be triggering at least... but they aren't. This situation is part of an Ionic Framework project, though I doubt that's the root cause.

Answer №1

getContacts() is defined as a function, but where is it being invoked? You should call getContacts() somewhere within the controller:

angular.module('NextShift')
    .controller('ContactsCtrl', ['$scope', '$rootScope', 'Auth', '$localStorage', '$stateParams', 'contactFactory',
        function($scope, $rootScope, Auth, $localStorage, $stateParams, contactFactory) {
           console.log("I reach this point");

           function getContacts() {
                contactFactory.getContacts()
                .success(function(contactList) {
                    console.log("Why am I not reaching here?");
                    $scope.contacts = contactList;
                })
                .error(function(error){
                    console.log("Am I missing something?");
                    $rootScope.error = "Failed to retrieve contacts";
                });
           }

           // do something else
           getContacts();
       }
]);

Adding spaces before and after each function declaration can aid in visually organizing the code and prevent such oversights.

Note: if you want to call getContacts() for example from ng-click="getContacts(), you must assign it to a $scope variable like this:

$scope.getContacts = function() {....}

Note: I have corrected your dependency declaration for the controller - your previous method could lead to errors when using one of the dependencies.

Answer №2

Before diving in, it's important to declare your dependencies as strings (before writing the function) - ensuring they are all listed in the correct order.

.controller('ContactsCtrl', ['$scope','contactFactory',
function($scope, $rootScope, Auth, $localStorage, $stateParams, contactFactory)

should be:

 .controller('ContactsCtrl', ['$scope', '$rootScope', 'Auth', '$localStorage', '$stateParams', 'contactFactory',
function($scope, $rootScope, Auth, $localStorage, $stateParams, contactFactory)

Another key step is to initialize 'get contacts' within your controller. Simply add:

 getContacts();

at the end of your controller script for it to start running when the controller loads.

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 way to determine using code whether or not an iframe will be blocked by a website?

I'm creating a script that dynamically generates multiple iframes loading random websites. I am curious if there is a way to check programmatically if a website blocks being iframed, so I can display a thumbnail of the site as an alternative. Can this ...

Managing multiple markers using the LayersControl.Overlay in React Leaflet

I am working on a project that involves displaying multiple public facilities in a city on a map, each represented by a marker. I want to implement a feature where users can filter these facilities based on their typology using checkboxes. Each typology wi ...

`In JavaScript strict mode, overridden function fails to execute`

I'm facing an issue where a modified function is not being called. The original implementation is shown below. // Base file defining and exporting a function function a() { // do something } module.exports = { a: a, b: function () { ...

Having trouble with my React Next app, it's giving me an error stating "window is not defined

Currently, I am developing in Next.js using React components and encountering an issue. I keep receiving a ReferenceError: window is not defined error in react-location-picker. If you need to check out the package, here is the link: react-location-picker ...

Parsley Herb: Radio Message "Item 73 does not support the 'replace' function"

Struggling to integrate parsley.js into my dynamic form. When I press the submit button, which triggers a JavaScript event, I execute: var validateForm = $('#myForm').parsley().validate(); However, it's not functioning properly as there is ...

Finding the distance between two coordinates using Mapbox is easy once you understand how to utilize

Currently, I am in the process of learning how to utilize the Mapbox API within my node application. One of my objectives is to execute calculations on the backend, particularly obtaining the distance between two sets of coordinates. I'm struggling w ...

Using Webpack to transfer a function to the front-end

I am currently delving into the world of webpack and attempting to set up a basic integration. Within my file script.js, I have included some essential functions: scripts.js export foo = () => { console.log('foo') } export bar = () => ...

Changing visibility when class is removed with display: none

I have a collection of div elements, some of them are currently hidden using the class "not-updated", while others are visible. .not-update{ display: none } With certain AJAX calls, some of these hidden divs may become visible by removing the ...

HTML link with "mailto:" not opening in a new tab

Just posted for the first time! I'm attempting to create a mailto link using 'templated' JavaScript that pulls specific data from a JSON object: var menu = { "menu": [ { "title": "let's talk", "link": "mailto:<a href ...

Switch between every other pair of table rows, then repeat with the following two pairs

I am attempting to create a table with alternating row colors of green and yellow in sets of two. I have been using :nth-child but it is not working correctly. My table is automated using Angular 6 and styled with Angular Material 6. If you would like to ...

Problem encountered when working with several child HTML elements while utilizing Directives in AngularJS

I've been using a template to create a popup menu that displays alerts, and so far it's been working well. However, I wanted to add a manual alert option by including an input text field. But to my surprise, the input field seems to be disabled f ...

Error encountered in Angular CLI: Attempting to access property 'value' of an undefined variable

I am encountering an issue while trying to retrieve the values of radio buttons and store them in a MySql database. The error message I receive is TypeError: Cannot read property 'value' of undefined. This project involves the use of Angular and ...

How to send an HTML form using Angular 2/4 component after the first AJAX submit callback?

I am trying to submit a form to an external site using the POST method in a traditional way (non-Ajax). The submission is successful, however, Angular is throwing an error in the console before redirecting to the external page. Here is the HTML code I use ...

Converting a JavaScript variable into an xls or csv file

My application currently uses Javascript for calculations and data plotting, but I want to give users the ability to download the data as a csv or xls file. Is there a way in Javascript or another method where users can click a button, enter a filename, an ...

The configuration "react-app" failed to load, hindering the ability to extend it while working on the project

After creating a react app using yarn create react-app, I ran yarn start and the project loaded fine on localhost. However, any edits made to a file (such as adding a new tag or renaming the contents of a div) caused the app to throw an error during compil ...

What is the best way to utilize JavaScript methods for retrieving dynamic data?

My variable needs to return data based on an array of objects that contain dynamic dummy values. There are 3 sets of dummies structured as follows --> Example: dummy1_A, dummy1_B, dummy1_C, ... dummy2_A, dummy2_B, dummy2_C, ... dummy3_A, dummy3_B, du ...

finding the source file or code where a particular html element is being generated

In the HTML file I have, there are multiple JavaScript files added. Whenever I run the HTML file, a title tag is automatically created in my HTML file. I do not want this title tag to appear in my HTML file. How can I prevent this from happening? Or how c ...

Having trouble showing my Google map using canvas

Can anyone help me with this issue that I'm facing? I am working on a JavaScript web page and trying to show a Google map (Google API) along with a canvas tag in the html body. Currently, the map and canvas are only displaying separately. https://i ...

Youtube does not trigger injection scripts in Safari extensions

During my work on a Safari extension, I encountered an issue with adding an End Script to Youtube pages. The script functions properly when the initial Youtube page loads, but if I click any links within the page, nothing happens unless I open them in a ne ...

Loading data into a Dojo ItemFileReadStore using Grails and the "render as JSON" method

I have developed a controller method that generates a JSON "file" on-the-fly when the corresponding URL is accessed. This file exists in memory and not saved on disk, as it's dynamically created when the URL is hit. I'm attempting to utilize this ...