Tips for successfully transferring $scope to $factory

Hey there! I'm new to AngularJS and I'm trying to figure out how to pass my empty $scope to my $factory for dynamic login functionality. I'm using $http to retrieve data from my API and I attempted to assign the scope in the factory, but it didn't work as expected.

Here's my serviceAPI:

(function() {
    "use strict";

    angular.module('starter').factory(serviceAPI', function($http, $q, $ionicLoading, $timeout) {

        function getData() {
            var deferred = $q.defer();
            $ionicLoading.show({ template: 'Loading...' });
            var url = "myAPI";

            var data = {
                username: "admin", <-- I want to make this dynamic
                password: "admin" <--
            };

            $http({
                method: 'POST',
                url: url,
                data: data

            }).success(function(data) {
                $ionicLoading.hide();
                deferred.resolve(data);

            }).error(function() {
                console.log('Error while making HTTP call');
                $ionicLoading.hide();
                deferred.reject();

            });

            return deferred.promise;
        }

        // Return value to public
        return {
            getData: getData,
        };
    })

}());

This is the controller:

(function() {
    "use strict";

    angular.module('starter').controller('LoginCtrl', ['$scope', 'serviceAPI', LoginCtrl]);

    function LoginCtrl($scope, serviceAPI) {
        $scope.username = "";
        $scope.password = "";
        $scope.login = function() {
            serviceAPI.getData().then(function(data) {
                console.log(data)
            });
        }
    }

}());

Answer №1

using service API

function retrieveUserData(userName, pass) {
//...
var userData = {
username: userName,
password: pass
};   //...}

within the controller ...

$scope.username = "";
$scope.password = "";
$scope.authenticateUser = function() {            
serviceAPI.retrieveUserData($scope.username,$scope.password).then(function(userData) {
console.log(userData)
});

}

...

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

Testing inherit from a parent class in a unit test for Angular 2

Trying to create a unit test that checks if the method from the base class is being called This is the base class: export abstract class Animal{ protected eatFood() { console.log("EAT FOOD!") } } Here is the class under test: export ...

What is causing the extra whitespace on the right side with container-fluid?

Could someone assist me with an issue I'm experiencing when using the container-fluid in Bootstrap? It seems to be leaving some space on the right side of my web page, and as a newcomer to Bootstrap, any help would be greatly appreciated. <link ...

Adjust the height of the container div for the carousel according to the length of the text displayed

My image carousel features description content positioned on the right for wide-screen windows. However, I want the description to shift below the images when the browser window reaches a certain breakpoint. The challenge I am facing is that the height of ...

Navigating through PWAs and implementing deep linking in both single page applications (SPAs) and multi-page applications

QUESTION: How can navigation, history, and deep-linking be managed in a PWA without relying on a heavy JS Framework? Tasked with transitioning an existing shopping website from Angular 1 SPA to a Multi Page App (MPA) PWA, I find myself grappling with desi ...

Is there a way for my discord bot to notify me when a certain user is playing a particular game?

How can I set up my bot to automatically send a message when a specific user starts playing a specific game, like Left 4 Dead 2? I'm looking for a way to do this without using any commands. // Game Art Sender // if (message.channel.id === '57367 ...

How to delete tabs generated dynamically in jQuery UI

Is there a way to efficiently delete tabs that have been dynamically generated using the jQuery UI library? The documentation for the library doesn't provide clear instructions on how to go about removing tabs. I specifically need to know how to delet ...

Organizing various response data in an array-type JavaScript variable

Seeking assistance please.. I have successfully created a function to retrieve all supplier data from the database. However, I now want to create javascript variables in array format to store this information. For example - one array for supplier_id and an ...

What is the purpose of the j function in the Rails framework?

While reading a blog, I stumbled upon a mention of a j function in Rails. The author was using it for ajax style page updates. $('#cart').html("<%=j render @cart %>"); I understand that they are using partials to render the cart partial, ...

Utilize Angular to connect NavBar partial HTML with a controller variable

Encountering an issue where my search term in the navigation bar is not binding to a controller variable due to it being out of scope. Attempting to utilize ng-model in the partial HTML navbar to connect the input value with the controller variable. Parti ...

Exploring the world of logging in Nestjs to capture response data objects

I'm eager to implement logging for incoming requests and outgoing responses in NestJs. I gathered insights from various sources including a post on StackOverflow and a document on NestJs Aspect Interception. I'd love to achieve this without rely ...

Preventing multiple users from saving the same value for a field using ajax and C#: Best Practices

On my aspx page, I am collecting email addresses from users and making an ajax call like so: function CheckEmailExistence() { $.ajax({ url: "Handler.ashx", contentType: "application/json; charset=utf ...

Using JavaScript's indexOf method with multiple search values

I have a data set that includes various duplicate values ["test234", "test9495", "test234", "test93992", "test234"] I am looking to find the positions of every instance of test234 in the dataset Although ...

Is it possible to showcase multiple items in react JS based on logical operators?

How can I update the navigation bar to display different menu options based on the user's login status? When a user is logged in, the "Logout", "Add Product", and "Manage Inventory" options should be shown. If a user is not logged in, only the "Home" ...

Incorporate conditional components into a React state object

I have a variable called myVar that holds an array of values. I am trying to selectively add elements to the array based on a specific condition. For example: If the condition is met: myVar = [1, 2, 3] Otherwise: myVar = [1, 2, 3, 4, 5] In both cases ...

Navigating JSON/API data within a Vue.js component template: step-by-step guide

I've successfully implemented a code snippet that renders a list of songs here: https://jsfiddle.net/jeremypbeasley/guraav4r/8/ var apiURL = "https://ws.audioscrobbler.com/2.0/?method=user.gettoptracks&user=thisisheroic&period=7day&limit= ...

The JSON response is being overridden by a catch-all URL and ends up being displayed as a 404 error page

I'm dealing with a React/Express setup that looks something like this (simplified for clarity): const path = require('path') const express = require('express') const CLIENT_BUILD_PATH = path.join(__dirname, '../build') ...

What is the process of initializing divs in DataTables?

My application has a DataTable installed, but I encountered an error message stating "DataTables warning: Non-table node initialisation (DIV). For more details about this error, please visit http://datatables.net/tn/2". I'm aware that DataTables is d ...

Halt the program's process until the ajax request has finished

Struggling with what seems like a common issue of the "Asynchronous Problem" and finding it difficult to find a solution. Currently, I am working on a custom bootstrap form wizard which functions as tabs/slideshow. Each step in the wizard is represented b ...

Obtaining a string value from a parallel array

Apologies for the very basic question, but I'm struggling with this. I have a word. Each letter of the word corresponds to a position in one array, and then returns the character at the same position from a parallel array (basic cipher). Here is my c ...

Ionic 5 page div within ion-contents element is experiencing scrolling issues on iPhone devices

My application features a div element containing an ion-slides component. The ion-slides component houses several ion-slide elements that slide horizontally. Here is the relevant code snippet: <ion-content [scrollEvents]="true"> <div ...