Using AngularJS to invoke a method within $routeProvider

I am relatively new to AngularJS and I have a straightforward question that I can't seem to find the answer to. Below is my code snippet:

angular.module('app', ['app.controllers', 'ngRoute']).
config(['$routeProvider', function ($routeProvider) {
    $routeProvider.when('/users', {templateUrl: '../pages/list.html', controller: 'UserListCtrl'}).
        when('/user-details/:login', {templateUrl: '../pages/form.html', controller: 'UserCtrl'  /* and here I need to call userDetails(login) from UserCtrl */}).
        otherwise({redirectTo: '/users'});;
}
]);

app.controller('UserCtrl', function ($scope, $http, $location) {
$scope.userDetails = function (login) {
    $http.get(url + login).success(function (data) {
        $scope.user = data[0];
        console.log('tst');
    }).error(errorCallback);
};

$scope.createUser = function (user) {
    $http.post(url, user).success(function (data) {
        $location.path('/users');
    }).error(errorCallback);
};
});

My issue lies in figuring out how to call a specific method of a controller when the routing matches. I need to pass a parameter, specifically :login from the routing, to this method. Any suggestions on how to solve this puzzle would be greatly appreciated. Thank you for your assistance.

Answer №1

It seems like you're trying to utilize the same controller for two distinct parts of the view - one for creating a user and another for retrieving the current user's details.

However, it's best practice to separate these functionalities into different controllers rather than using the same one. Common or reusable functionality should be extracted into a service to promote better organization and maintainability.

In addition, any backend calls should be handled within services and not directly inside controllers. Here's an example:

app.service('UserSrv', function ($http) {
    var url = '...';
    this.userDetails = function (login) {
        return $http.get(url + login);
    };
    this.createUser = function (user) {
        return $http.post(url, user);
    };
});

app.controller('UserCtrl', function ($scope, UserSrv) {
    var login = '...';
    var errorCallback = ...;

    // Fetch user details on initialization
    UserSrv.userDetails(login).success(function (data) {
        $scope.user = data[0];
    }).error(errorCallback);
});

app.controller('NewUserCtrl', function ($location, $scope, UserSrv) {
    var errorCallback = ...;

    $scope.createUser = function (user) {
        UserSrv.createUser(user).success(function (data) {
            $location.path('/users');
        }).error(errorCallback);
    };
});

An alternative approach could involve leveraging $routeProvider's resolve property to prefetch the user's details and pass them as an argument to the UserCtrl.

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 Countdown Timer in React Native triggers an error due to Invariant Violation

According to some expert advice from this stackoverflow answer, I attempted to implement a countdown timer for my project as shown below. constructor(props: Object) { super(props); this.state ={ timer: 3,hideTimer:false} } componentDidMount(){ this. ...

Conceal component while navigating in VueJs

I am working on a Vue project. I am trying to implement a feature where a component is hidden while the user scrolls, but then reappears once the scrolling stops. I have tried using a scroll event, but the component does not show up again. <div c ...

How can a splash screen be created in Angular 5 that stays active until all images are loaded by the child component?

I am incorporating angular 5 to present pages containing numerous high-resolution images, but unfortunately, the loading time is quite lengthy. My goal is to create a splash screen, which is essentially a full-screen div that will vanish once all images ha ...

Triggering the click event three times on a dynamically generated element

I am currently facing a simple issue. I am attempting to implement a click event on dynamically generated elements such as this: $(document).ready(function(){ $('ul').on('click', 'li.clickable', function() { conso ...

I require further clarification on how to target a specific element within the markup code

Currently, I am participating in an online class where the instructor demonstrated how to target a <button> element using document.querySelector. The method the tutor used was selecting the parent element and that's it. <div class="row&q ...

Is it possible to keep a popup modal visible even after a user has logged in?

There is a piece of code that restricts users from viewing our "pricing popup" until they log in. However, once the user logs in, I want the pricing popup to reappear as if the login never occurred. Ideally, the user shouldn't have to click again to o ...

Getting the JSON representation of base64 data from a list of files

After retrieving a file list, I aim to transform it into a JSON array similar to: [ {"name":"IDCard001.jpg","base64":"data:image/jpeg;base64,/9j/4AA.."}, {"name":"IDCard002.jpg","base64&q ...

The Fusionchart AngularJS component is unable to display a graph using JSON data retrieved from a URL

I am utilizing Fusion Chart for AngularJS to display data coming from a JSON URL using HTTP Angular (with my factory). Here is the JSON object: {"chart":{"caption":"Asset Hardware by Status","numberPrefix":"","dataFormat":"json","theme":"fint","showBorder ...

Tips for executing an npm command within a C# class library

I am currently developing a project in a class library. The main objective of this project is to execute a JavaScript project using an npm command through a method call in C#. The npm command to run the JavaScript project is: npm start The JavaScript ...

Achieve a stunning visual effect by gradually blending the background image in a parallax

Adding some parallax scrolling background images to my site using this awesome plugin: Looking to achieve a fade out effect on user scroll, similar to what is seen on this cool website: Tried implementing the code below but it doesn't seem to work d ...

Sinon Stub generates varying values with each invocation

I'm pretty new to TypeScript and JavaScript, but I've managed to create a functioning VScode extension that I'm really happy with. However, I'm running into some issues with my Mocha tests. Here's a snippet of the code I'm str ...

Saving JavaScript variables to a JSON file

In my possession is a JSON file named example_json.json, which contains the following data: { "timeline": { "headline":"WELCOME", "type":"default", "text":"People say stuff", "startDate":"10/4/2011 15:02:00", ...

Can you help me address the #tag in the URL for an AngularJS website?

At the moment, my website URL looks like this: example.com/#/services I need the new URL to look like this: example.com/services Basically, I want to remove the # tag from the website URL. Could someone please explain how I can resolve this URL is ...

Determining the necessary data to send via ajax for a particular issue

Currently, I am learning JavaScript and have encountered another challenge along the way. I am looking for assistance in understanding the concept, whether it is a solution in jQuery or Angular. I have two types of tasks in my HTML - audio or graphic. The ...

implementing AJAX functionality in Laravel when a drop-down item is selected

Hello there, I am a newcomer to the world of coding and I'm currently learning Laravel for a personal project. My goal is to retrieve data from a database based on the selection made in a dropdown menu. Here's the code for the dropdown menu: < ...

Creating Reusable Controllers in AngularJS: A Step-by-Step Guide

I am encountering a situation in my application where multiple controllers share identical functions such as InitMenu, GetData, Search, and Paging. Is there a way to create a universal controller that includes these core functions without the need to manu ...

Unable to extract the 'id' property from 'params' object in Next.js 13.4 due to its undefined value

I am currently trying to retrieve the [id] URL parameter in Next.js 13.4, but I keep encountering an error stating that params is undefined. Despite extensive online research and seeking assistance from ChatGPT, all I could find were examples for older ve ...

Exploring Password Verification Techniques in JavaScript

I'm struggling with a password comparison issue in JavaScript. It was working fine on my previous project, but for some reason it's not working now. Here is the HTML code: <form> <label> <strong>Username</ ...

What are the steps to utilize chrome.tabs.onUpdated.addListener?

I am currently working on a Chrome extension where I need to display an alert() showing the page URL whenever the user switches tabs or enters a new URL in a tab. However, my current implementation is not functioning as expected: chrome.tabs.onUpdated.ad ...

Is there a way to exclusively use ES6 to import jQuery from an npm package?

After installing jQuery using npm -install jquery, a node_modules folder was created in my project with the jQuery library inside. However, I encountered an error when trying to import it using ES6 import. I am looking for a solution that does not involve ...