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

``There seems to be an issue with setting the input value attribute using jQuery's .html

I've been trying to update the value attribute in the input element within my HTML code, but so far, I haven't had any luck with it. HTML: <div class='photo-info'> Photo Name : <span class='photo-name'><?p ...

Binding Data in Vue Multiselect

After extensive searching, I stumbled upon an amazing searchable select Vue component that has caught my eye: https://github.com/monterail/vue-multiselect. However, there seems to be a small issue when it comes to feeding it an array of objects as options ...

Display a pop-up upon clicking a button

I've created a custom popup form using Flodesk and added the corresponding Javascript Snippet to my website just before the closing head tag. <script> (function(w, d, t, h, s, n) { w.FlodeskObject = n; var fn = function() { (w[n] ...

Using PHP, show a specific table row when clicked by matching the ID

I am currently developing an application for a school project that manages tests. This app allows employees to log in, select a client, register clients, and conduct tests with them, all while storing the data in a database. I have successfully implemente ...

Typescript: organizing nested types within an interface

My goal is to create an interface CountersData based on my JSON data. The challenge lies in the nested id property, which contains an array of nested dictionaries. I want this property to be optional. However, I have not been successful in making it option ...

Guide to emitting a value using the composition API

I'm currently working with a datepicker component that is part of a form in my Vue3 app using the composition API. My challenge is how to pass a value from the datepicker component back up to the form component. Unfortunately, I've encountered ...

Searching for ways to filter out specific tags using regular expressions

Can anyone provide a quick solution to help me with this issue? I am trying to remove all html tags from a string, except for the ones specified in a whitelist (variable). This is my current code: whitelist = 'p|br|ul|li|strike|em|strong|a', ...

Two components, one scroll bar, both moving within the same plane

For those interested, here is the JSFiddle link for further exploration: https://jsfiddle.net/q6q499ew/ Currently, there is a basic functionality in place where when you scroll past a certain point, an element becomes stuck until you start scrolling back ...

There seems to be an issue with the Alexa skill's ability to provide a response after another

I am currently developing an Alexa skill that involves a multi-step dialog where the user needs to respond to several questions one after the other. To begin, I am trying to kick things off by implementing a single slot prompt. I am checking if the slot is ...

Assign specific CSS classes to elements based on the v-model value in Vue.js

Looking to create a dynamic table using Vue and trying to add a class to a row when a checkbox is checked. Each checkbox is associated with a specific value in an object of objects. View the code on Codepen. <tbody> <tr v-for="row in filter ...

Maintain the selected list item after filtering in AngularJS

I am facing an issue with highlighting selected items in a list. I have three first names: Roy, Sam, David displayed in a ul as list items. Initially, I can toggle each li on click just fine. However, after performing a search and returning to the list, th ...

What is the process for using the CLI to downgrade an NPM package to a previous minor version by utilizing the tilde version tag?

I currently have Typescript version ^3.7.4 installed as a devDependency in my project's package.json: { "name": "my-awesome-package", "version": "1.0.0", "devDependencies": { "typescript": "^3.7.4" } } My goal is to downgrade Typescript ...

What is the best way to incorporate data from JSON objects in nested arrays within an array into HTML using AngularJS?

I have been struggling to display the JSON data in list.html in the desired format. Despite trying different approaches from similar posts, I have not been successful as my JSON structure is unique. How can I ensure that fields such as givenName, familyNam ...

Utilizing Multiple MongoDB Connections in a Node.js Application

I am facing an interesting challenge in my Node.js project where I need to connect multiple MongoDB databases. Let me share with you my current setup and the issue that is causing me some trouble. Node Version: v6.12.1 Express.js Version: 4.16.2 Mongoos ...

Challenges encountered when attempting to send an array in res.json with the MERN stack

I am facing a challenge while trying to make two separate model calls using the MERN stack. The issue arises when I try to send an array in res.json; extracting the data seems to be problematic. On examining the console log: {data: "[]", status: ...

creating a function within an object that allows for chaining

My goal is to create a chainable object, but I am struggling to implement this in a function. This is the functionality I desire: $donate.ga('testing').go(value); The code for my object currently appears as follows: var $donate = { ga: fu ...

The quickest regular expression match possible if it is already a subsection of another match

Is there a simple way to find the shortest match in a long text where strings are repeated? I'm having trouble because matches within already matched text aren't being found. Here's an example of the issue: Using code: "ababc".match(/a.+c ...

Unraveling HTML elements within a string using MongoDB: A step-by-step guide

Currently, I am in the process of creating a blog from scratch as a way to enhance my skills. The posts' content is stored as a long string in MongoDB with some random HTML tags added for testing purposes. I am curious about the conventional method fo ...

Issue occurs when a circle element is not following a div element on mouse

Currently, I have implemented some jQuery code that instructs a div named small-circle to track my cursor movement. I discovered how to accomplish this by referencing a thread on stack overflow. I made slight modifications to the script to suit my specifi ...

Ways to substitute the $(document).ready function?

I'm facing a problem and struggling to find a solution. Here is the JavaScript script that's causing me trouble: $(function () { $.ajaxSetup({ cache: false }); var timer = window.setTimeout(function () { $(".alert").fadeTo(10 ...