Questions about setting up a controller in AngularJS

As I dive into my first AngularJS controller within a test application, I am encountering some challenges.

I am retrieving a list of items from a RESTful web service and working on implementing basic CRUD logic for these items.

The item list is displayed in the itemsList.htm page and the routing configuration is set as follows:

app.config(function ($routeProvider) {
    $routeProvider
        .when('/items',
            {
                controller: 'ItemsController',
                templateUrl: 'app/Partials/itemsList.htm'
            })
        .when('/items/:itemID',
            {
                controller: 'ItemsController',
                templateUrl: 'app/Partials/editItem.htm'
            })
        .otherwise({ redirectTo: '/items' });
});

Next, I have defined my ItemsController:

app.controller('ItemsController', function ($scope, $routeParams, $location, itemsService) {
    $scope.status;
    $scope.items;

    getItems();

    function getItems() {
        itemsService.getItems()
            .success(function (items) {
                $scope.items = items;   
            })
            .error(function (error) {
                $scope.status = 'Unable to load items: ' + error.message;
            });
    }

    function getItem(ID) {
        // ...  
    }
}

Now, my goal is to expand this controller by adding a function that fetches a specific item based on its ID and populates the editItem.htm page. However, I am unsure how to access this function...

Essentially, how can I link the path /items/:itemID to this function? Should I separate it into a different controller and adjust the route configuration?

NOTE: In my usual web development practice utilizing Java and Spring MVC, I typically create a single controller for each entity in the application (e.g., ItemsController, CustomersController, etc.). Is it advisable to follow the same approach with AngularJS, or are there other best practices to consider?

Answer №1

My approach would involve creating an ItemController specifically designed to handle individual items. The implementation may vary depending on the structure of the html.

Regardless, you will need to extract the ID of the selected item using the $routeParams collection.

Within the controller, you can execute the following:

if($routeParams.itemID) {
   // Retrieve the item ID and call getItem
   getItem(itemID).success(function(item) {
       $scope.item=data;
   });
}

This code snippet should be incorporated into either the ItemsController (if it's the same controller being used) or a new controller that follows the same logic.

If you are utilizing the existing ItemsController, the implementation would look like this:

 if($routeParams.itemID) {
       // Implement same functionality as shown above
 }
 else {
     getItems();
 }

This setup ensures that the list is not loaded into the scope when viewing a single item.

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

When IntelliJ starts Spring boot, resources folder assets are not served

I'm following a tutorial similar to this one. The setup involves a pom file that manages two modules, the frontend module and the backend module. Tools being used: IDE: Intellij, spring-boot, Vue.js I initialized the frontent module using vue init w ...

Insert a blank row at the top of the grid in Wijmo for Angular 2

I am attempting to insert a new empty row at the start of the grid when an external button is clicked. The grid is displaying correctly. <wj-flex-grid #flex [itemsSource]="data" [isReadOnly]="true" [headersVisibility]="'Column' ...

What is the process for obtaining a value when you click and then retrieving the associated ID?

I am looking to create a function that, when clicking on the square with the ID "colors", will return the sentence containing the colors from the table in PHP files with the ID "retours_couleurs". Apologies for any mistakes in my English, as I am French. ...

Why are my values not being applied to the model class in Angular 7?

I'm currently developing an online shopping website where I have defined my order Model class as shown below: import { User } from './user.model'; export class Order { constructor(){} amount: Number = 0; status: String = ""; date: ...

Error Message: Unexpected Type Error with axios in Vue 3

Trying to implement axios in my Vue3 project for fetching APIs. Here is the code snippet from my component: export default { name: "Step2", data() { return { loading: true; }; }, mounted() { this.loading = false; }, ...

How do I navigate to a different page in a Flask app after an ajax post depending on a condition detected in the view?

Within my flask application, I have a sales page where users can input information that is then saved to the database using an ajax post request. The twist is that there are only a limited number of consoles available for users to record their sales. If on ...

Tips for utilizing navigator.getDisplayMedia with automatic screen selection:

navigator.mediaDevices.getDisplayMedia({ audio: false, video: true }).then(gotMedia).catch(function(e) { console.log('getDisplayMedia() error: ', e); }); Triggering the above code will result in a popup like this. There is anoth ...

Unlock the full potential of knockout.js by mastering how to leverage templates recursively

Given the following model and view model for nested categories: function Category(id, name) { var self = this; self.Id = ko.observable(id || '00000000-0000-0000-0000-000000000000'); self.Name = ko.observable(name); self.children ...

Identifying Changes in ReactJS Pages

As I delve into learning ReactJS, I have been experimenting with various websites that utilize this technology. Presently, my focus is on making an AJAX call to an API based on the URL of a page. The issue arises when clicking a link breaks my code due t ...

Guide to clearing input fields and displaying an error message through Ajax when the requested data is not found within a MySQL database

I am looking for a way to clear the textboxes and display an alert message if the data is not found in the MySQL table. I encountered an issue when using type: 'json' as removing it makes the alert work, but then the data from the MySQL table doe ...

What is the best way to send an array to the server with $http in AngularJS?

I have a collection of unique identifiers that I need to send to the server. Most online solutions suggest passing these identifiers as query parameters in the URL, but this approach is not ideal for me as there could be a large number of identifiers invol ...

Tips on leveraging dynamic queries in your REST API usage

As a new Javascript learner, I am experimenting with creating a basic rest api using node.js. Currently, I have set up a database called testDb and a table named testMeasurement in influxdb. The testMeasurement table consists of the columns DateOfBirth, ID ...

Challenges faced when updating a value in AngularJS

I am encountering an issue where the values in the view of my angularJS page are not updating as expected. The goal is for these values to change after calling a specific method on the website. The HTML element displaying the value is: <p>Current s ...

Gulp is ensuring the destination file remains unchanged

I'm encountering an issue with gulp in my project. I've set up a process to automate the compilation of source and styles into a single file using gulp. However, I'm facing a problem where it doesn't want to overwrite the `application.j ...

The AngularJS dependency injection system allows developers to easily manage dependencies using arrays and the $inject

Being new to angularJS, I'm seeking some insight on dependency injection. After some research, here's what I've gathered: I have 2 service files (using factories): -mogService.js angular.module('anglober.services').factory(&apo ...

Unexpected loading glitches occurring in vue-material components

I recently delved into the world of Vue.js and VueMaterial, which has been a refreshing and new experience for me since I've mostly focused on Native Android development in the past. Currently, I'm facing an unusual issue that seems to stem from ...

Breaking Long Strings into Multiple Lines Using React Material UI Typography

Currently, I am working with ReactJS and incorporating MaterialUI components library into my project. However, I have encountered a problem with the Typography component. When I input a long text, it overflows its container without breaking onto a new lin ...

Developing Attributes in JSON

Greetings stackOverflow Community, I'm struggling a bit with creating JSON objects. I have code snippet that is meant to populate a list called members with names, and then add a property to each of those names. Here is the specific snippet in questi ...

Issue with React and JavaScript: Object is displayed on the console briefly before disappearing

I am having an issue with my sign up page where the console log of the two fields disappears after a second. I would appreciate any assistance on this matter. Below is the code for the sign-up form: export default function SignUp() { const [firstNam ...

Use ajax to dynamically update the contents of a textbox

As a newbie programmer, I recently created my own JavaScript update function for my program. However, the code is not updating as expected. Can someone please help me troubleshoot and get it working properly? What I want to achieve is that when I change t ...