Trigger a route change in AngularJS via ng-click by passing a parameter

I am trying to update the route of an angularJS application built with the Ionic framework, but for some reason, the route is not changing

Here is a snippet from my app.js file:

angular.module('starter', ['ionic', 'starter.controllers'])
.state('app.annuaire.menuitempage', {
  url: "/menuitempage/:ID",
  views: {
    'menuContent' :{
      templateUrl: "templates/menuItemPage.html",
      controller: function($stateParams){
      $stateParams.ID  ;
     }
    }
  }
})

.state('app.annuaire', {
  url: "/annuaire",
  views: {
    'menuContent' :{
      templateUrl: "templates/annuaire.html",
      controller: 'MenuItemCtrl'
    }
  }
})   

Furthermore, here is the code snippet from my controller:

  angular.module('starter.controllers', [])
  .controller('MenuItemCtrl', function($scope, $http, $location) {
    $scope.itemsMenu = {};

            var responsePromise =   $http.get("http://monguidepratique.com/mobile/getCategories.php?parent_id=0");

            responsePromise.success(function(data, status, headers, config) {
                //alert(data);
                $scope.itemsMenu = data;
            });
            responsePromise.error(function(data, status, headers, config) {
                alert("AJAX failed!");
            });
   $scope.itemClick = function(path){
            alert(1);
            $location.path(path); 

            };  

   }) 

Lastly, this is the HTML snippet from annuaire.html:

 <div class="col"  ng-click="itemClick('/menuitempage/1628')"><img class="img_menu" src="img/home.png"><p class="titre_center">Accueil</p></div>

Answer №1

Give this a shot

$location.path(path)

instead of using

$state.go(path)

To make it work, you must include the $location service in your controller.

Update

If you opt for using $state.go, do it like this:

$scope.itemClick = function(id){
  $state.go('app.annuaire.menuitempage', {'ID': id})
}; 

Also update your HTML accordingly:

<div class="col"  ng-click="itemClick(1628)"><img class="img_menu" src="img/home.png"><p class="titre_center">Accueil</p></div>

Remember, the first parameter is the state name, not the URL. The second parameter should be an Object with your desired parameters.

Answer №2

After some troubleshooting, I was able to find a solution to my issue.

Within the annuaire.html file, I made the following modification:

itemClick('/menuitempage/1628')

I updated it to:

itemClick('/app/menuitempage/1628') 

Additionally, I adjusted the route name from app.annuaire.menuitempage to:

app.menuitempage 

.state('app.menuitempage', {
  url: "/menuitempage/:ID",
  views: {
    'menuContent' :{
      templateUrl: "templates/menuitempage.html",
      controller: 'SubMenuCtrl'
    }
  }
})

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

Trouble obtaining output from chrome.tabs in browser console

Currently, I am experimenting with the browser's console and attempting to retrieve all the details of the active tabs. In order to do so, I open the browser's console and input the following: However, I encountered the following error: VM713:1 ...

Guide for adding a record to sqlexpress with javascript on aspx pages

Does anyone know how to use JavaScript in an ASPX file to insert a record into SQLExpress? ...

Using the angularjs-google-maps library to implement ng-click functionality within a marker

Regarding the angularjs-google-maps query, access more information at https://github.com/allenhwkim/angularjs-google-maps How can I trigger ng-click on a marker to set a variable? Currently, when clicking the marker, ng-click does not activate as expected ...

What is the process for entering a menu and displaying the information without storing it in the database?

https://i.sstatic.net/N8MnO.png In my project, I have a form input menu and quantity section (highlighted by the yellow line in the image). Once the user submits the data, it is displayed on a table (highlighted by the red line in the image), but it is no ...

Enhance D3 Version 6 Stacked Bar Chart with Spacing and Interactive Features

My bar chart lacks the spacing between bars that I intended to achieve, and the interactive tooltip doesn't show up when hovering over the bars. I could use some assistance with this. The purpose is to display the value of a specific color when hoveri ...

Adding external stylesheets or libraries in Express is a simple process that can greatly

Currently, I am in the process of developing a todo application using the express framework on a node server. The starting point for my application is an index.ejs file located in the same folder as my jquery.min.js file. However, when I attempt to include ...

Guide to moving a 3D model and initiating animation in threejs when a key is pressed

In the midst of a project where a person (gltf object) walks based on key presses, I have successfully updated the object position accordingly. However, I'm encountering difficulty in rotating the object when the left/right keys are pressed and ensur ...

Transforming React Redux reducer to hooks for a more modern approach

I am in the process of creating a login and registration application. I need to change a reducer that is currently being used for a class-based component to work with hooks instead. Here is the existing reducer: import { SET_CURRENT_USER, USER_LOADING } fr ...

Developing a buffer entity from a Javascript/Nodejs fetch response

Struggling with creating a buffer object to manipulate/parse through JSON response fetched via API. My fetch code is functional: const fetch = require("node-fetch"); const asset = 'Build_Artifacts' const url2 = 'http://localhost:8081/se ...

When reloading the Javascript React application, the "fetch" function is returning 'undefined' in the browser. However, when the application is reloaded directly from the API, it successfully

I am currently working on a component that retrieves a JSON object from GitHub using an asynchronous function. Here is the code snippet: async function getQueryJson(URL) { await fetch(URL) // This gets the git commits .then((res) => res.json()) // ...

Please explain the purpose of the .forEach statements listed below

Describe the functionality of the two forEach loops provided in the code snippet below. Also, is 'col' a predefined property for arrays? var width = data.length, height = data[0].length; data.forEach(function(col){ col.forEach(function(v ...

What is the best way to navigate to the next video in my YouTube API search results with Vue.js?

After setting up a search component that sends data to the parent player.component, I pass the video id and an object containing 5 search results to the player.component. <template> <div class="mobile-screen"> <b-container> ...

What is the method of adding a child to the outerHTML of the parent element instead of within it?

Is there a way to use the outerHTML method on a parent element to append a child element so that the icons appear outside of the targeted element rather than inside it? The current code snippet shows the icons inside the box, but I want them to be placed o ...

Ionic not displaying Angular home route

This is my first time working with Ionic and Angular. Unfortunately, the home route is not functioning properly—the view is not being loaded, but other views are displayed. I suspect that the issue lies in the route itself because the URL is http://local ...

What is the best method for disseminating data to multiple stores with just a single action in the React flux architecture?

Is there a way to efficiently update multiple stores with data in one action? Imagine receiving post data from a server as a user action. Below is a simple pseudo code for this action: class UserActions { getPosts() { asyncFetch(apiEndPoint, ...

What causes an "Undefined index" error in jQuery when making AJAX requests?

Whenever I make an AJAX request in my main.js file, I encounter the following error message: Undefined index: id in sqlinfo.php on line 13 I am puzzled because I believe that I am populating the request object correctly. What's even more perplexing i ...

An easy guide to sorting outcomes using JSON

I have JSONResults in my Controller that contains all the data from a table. On the client's HTML detail view page, I am using JavaScript to fetch this data. How do I extract data from JSON where the client name is equal to klID (this is a JSON string ...

Discovering specific keywords within HTML tags and performing replacements using jQuery

I am searching for specific strings within my HTML code, and if I find them, I want to replace them with nothing. For example: HTML: <img src=`javascript:alert("hello ,world!")`> My goal is to locate keywords like javascript, alert, etc, within H ...

Utilizing dynamic values for filtering within two nested Ng-repeat directives in AngularJS

For the second ng-repeat, I want to filter based on a dynamic value obtained from the first ng-repeat. Below is my code snippet: <div ng-repeat="all in all | unique: 'Category'"> <p>{{all.Category}}</p> <div class=" ...

Enhance User Experience with React JS Multi-Select Dropdown Feature

I am dealing with 4 select dropdowns. The values selected should not be available in the remaining dropdown lists. Here is an overview of my state: this.state = { selectedDropdownArray: {}, dropdownArray: ['select', '1', &apos ...