Angular JS: Utilizing $routeProvider for handling dynamic URLs

Within my menu, I have various groups listed that a user may belong to. I've set up a template page so that when a user selects one of the GROUPS from the menu, the fields in the template change accordingly.

<li><a href="#"><i class="glyphicon glyphicon-folder-open"></i>Home </a></li>
<li><a data-toggle="collapse" ng-init="getAllGroupsofUser()" data-target="#groups">My Groups</a>
     <ul id="groups" class="collapse">
       <li ng-repeat="group in groupsofUser" ng-controller="groupsCTRL"><a 
           ng-click="openPage(group)">{{group.name}}</a>
        </li>
    </ul>
</li>

The menu successfully displayed the Groups. I am utilizing ng-view and $routeProvider.

My $routeProvider:

app.config(['$routeProvider',
   function($routeProvider) {
     $routeProvider
       .when('/', {
         templateUrl: 'home.html',
         controller:"MyController"
       })
       .when('/group/:groupname', {
         templateUrl: "groupTemplate.html",
         controller:"groupsCTRL"
       }).
       otherwise({
       redirectTo: '/'
     });
 }]);

My controller:

app.controller( 'groupsCTRL',[ '$scope', '$http' , '$location', '$routeParams' ,function($scope, $http,$location,$routeParams){

     $scope.groupeName= $routeParams.groupname;

     $scope.openPage = function(group) {
        $scope.groupselected = group;
          console.log( "group: "+$scope.groupselected.id);
          location.href = "#/group/"+group.name;
    }

}]);

My template:

<div class="row" >
      <h1 class="page-header">Groupe {{groupeName}} </h1>
</div>
<div class="row">
     {{groupselected.id}}
</div>

My issue is that while the groupeName is displayed, only the groupselected.id appears in the console (due to using

console.log( "group: "+$scope.groupselected.id);
).

Please assist me. I need confirmation that the group was passed to the page as I will need to display information about the selected group in the next step.

Answer №1

My solution was to develop a new RESTful Web Service specifically designed to retrieve the Group By Name, considering its unique nature.

// Obtain Group by Name
$scope.getGroupByName = function(groupname){
    $scope.group=[];
    $http({method: 'GET', url: '/getGroupByName/'+groupname}).
        success(function(result) {
            $scope.group = result.data; 
        }).
        error(function(data, status, headers, config) {
            // Handle errors that may occur
        });
};

This service allows me to input the group name and retrieve the associated group data.

Answer №2

Make sure to utilize $location.path instead of location.href. Remember that when making location changes, it is necessary to trigger the digest cycle.

Sample Code

$scope.changeLocation = function(section) {
    $scope.selectedSection = section;
    console.log( "Selected section: "+$scope.selectedSection.id);
    $location.path("/section/"+section.name);
    if(!$scope.$$phase) $scope.$apply();
};

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

Ajax operates by fetching data from a database without requiring large files to be retrieved

Every time I try to retrieve a file larger than 0.5MB from the SQL database using AJAX, an error occurs. What am I doing wrong here? $(document).ready(function () { loadFileData(); }); function loadFileData() { $.ajax({ type: "GET", ...

Navigate to a specific section on a different page while excluding a distance of X

I've implemented the script below to execute the action mentioned in the title. <script type="text/javascript"> var jump=function(e) { if (e){ e.preventDefault(); var target = $(this).a ...

What is the correct way to implement a callback in the .then() method of Node.js?

I am currently working with a nodejs module that fetches data from a mongodb database using the mongodb driver. The callback is passed to a specific function which returns a promise, but instead of returning the result in the .then() function, it passes th ...

Having difficulty converting an object into an iterable using an arrow function

Currently immersed in learning JavaScript, I successfully created a class and now find myself faced with the task of making it iterable. The Group class represents a collection of values, akin to a Set, equipped with methods for adding, removing, and che ...

The data retrieved through Ajax functions may vary between Chrome and Firefox browsers

There seems to be an issue with retrieving data from a POST request in different browsers. In Chrome, the data is returned successfully and appears as follows: {"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cdacaeaea ...

Optimal techniques for handling DOM manipulation by altering model objects within AngularJS controllers?

After studying the post below and spending some time exploring angular js, I have a simple question. The post: no dom manipulation from angular js controllers The main point (from the post): Avoid using controllers for manipulating the DOM — Controller ...

generate an object with the forEach method

When I receive data from a graphql query, my goal is to structure an object like the example below: const MY_DATA = [ { id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28ba', imageUrl: defaultUrl, name: 'Johann', } ...

upload the file onto the server

I am currently facing an issue with uploading files in an array to the server, as it returns undefined. However, upon checking the console log, I can see that there is an object present. My main problem lies in how to properly post on the server. Is there ...

Working with an undefined object in jQuery

Currently, I am delving into the realm of creating MVC5 web pages utilizing JQuery and Ajax. As part of an exercise, I developed the following function: <script language="javascript"> $.get("GetCustomersByJson", null, BindData); function Bi ...

Ways to update a nested object by utilizing the setState method

I have a situation where I need to modify the key/value pairs of an object in my state. Specifically, I need to add a key/value pair to the object with an ID of 13. Please refer to the attached photo for reference. Although I know how to use setState, I ...

Tips for implementing AngularJS tags within Laravel templates

It's common knowledge that Laravel has asset functions in templates, such as: {{ asset('images/148630374252566.gif')}} However, when attempting to use Angular JS variables in a Laravel template, an error is thrown: {{ currentPlaying.title ...

Unable to successfully transfer a document

I am looking to upload a file onto my server. Here is what I have attempted: <input (change)="uploadImage($event.target)" hidden accept="image/*" #uploadProfileImage type="file"> uploadImage(event) { const profileImage = event.files.item(0); t ...

Why do certain servers encounter the "Uncaught SyntaxError: Unexpected token ILLEGAL" error when loading external resources like Google Analytics or fonts from fonts.com?

Working on a variety of servers, I encountered a common issue where some externally loaded resources would throw an error in Chrome: "Uncaught SyntaxError: Unexpected token ILLEGAL". While jQuery from the googleapis CDN loads without any problems, attempt ...

What is the best way to enable the noWrap feature for a Typography component that is within an Alert or AlertTitle component?

My goal is to have a Typography component truncate overflowing text with an ellipsis. However, I am facing an issue where this doesn't work when the Typography component is nested inside an Alert component. Below is a snippet of the code in question: ...

Generating Interactive ng-models for Firebase Integration | Ionic Framework | Firebase Database | AngularJS

I am working on creating a new app feature that allows users to tag other registered users in a post. The concept is that when a user creates a new post, there will be a list of all available users with checkboxes next to each. The user can check off the ...

Display a message if the local storage is empty

Recently, I came across a javascript code snippet that is designed to save birthday data in local storage and then display the data within a div element. The current functionality only shows nothing if the storage is empty. However, I require it to display ...

Update submenu panel in jQuery Mobile version 1.4.3 following AJAX request

Hello there, I am currently in the process of developing my first JQuery Mobile website. One of the key features I have implemented is a panel for navigation. Each individual page includes the panel, along with an icon in the header that serves as the butt ...

Exploring the fundamentals of Express.js code base

I have been examining the express.js code and attempting to rewrite it to gain a better understanding of creating middlewares within a framework. However, the complex inheritance structure in the code is causing confusion for me. Here are some relevant co ...

Angular version 1.0.8 was resolved to angular 1.4.1 instead of 1.4.3

Incorporating both grunt and bower for dependency management in my project, I encountered an issue when trying to include an external library: https://github.com/ninjatronic/angular-base64 The hurdle I faced was its requirement of Angular #>= 1.0.8, w ...

The webpage becomes unresponsive and gets stuck when sending a stream of requests to the web server via ajax

I am currently working on creating a signal on the webpage that displays either a green or red color based on values retrieved from a database. However, when I send a request after 10 seconds, the page appears to freeze and becomes unresponsive. I am strug ...