Trigger controller redirection in AngularJS 1.5.0 by clicking on <tr> tag

Currently, I am facing an issue with my web page where I use the ng-repeat directive to populate a table with a list of companies. My goal is to have a functionality where clicking on a table row opens another page with a form to edit the selected company.

Here is a snippet of the html code for the page:

<table>
    <tr>
        <th>Name</th>
        <th>Address</th>
    </tr>
    <tr ng-repeat="company in companies">
        <td>{{company.companyName}}</td>
        <td>{{company.companyAddress}}</td>
    </tr>
</table>

Below is the controller responsible for handling the click event:

angular.module('companyApp.companyForm', ['ngRoute', 'ngResource'])
    .config(['$routeProvider', function ($routeProvider) {
        $routeProvider.when('/updateCompany/:companyId', {
            templateUrl: 'app/companyForm/companyForm.html',
            controller: 'UpdatedCompanyController'
        });
    }])
    .controller('UpdatedCompanyController', ['$scope', '$resource',
        function ($scope, $resource) {

        }]);

Despite my efforts, my attempts to redirect to a new page upon clicking on a table row have not been successful. I have tried using:

$location.url("#/updateCompany").search({id:company.id})

However, this only generates a URL without any actual redirection. I also attempted:

window.location.href = //...

But once again, I find myself redirected back to the default page upon clicking on a table item. Can anyone provide guidance on how I can successfully redirect to a new page upon clicking on a table row?

Answer №1

Essentially, when

$location.url("#/updateCompany").search({id:company.id})
is used, it will create a URL such as #/updateCompany?id=1, which may not match any of the conditions set in $routeProvider (as per the configuration provided in the question).

To resolve this issue, you can adjust the URL to match the pattern of a registered route in $routeProvider.

$location.url("#/updateCompany/"+company.id)

Alternatively, you can utilize $location.path to address the problem:

$location.path('/updateCompany/'+ company.id);

HTML Markup

<tr ng-repeat="company in companies" ng-click="redirect(company)">
    <td>{{company.companyName}}</td>
    <td>{{company.companyAddress}}</td>
</tr>

JavaScript Code

$scope.redirect = function(company){
    $location.path('/updateCompany/'+ company.id);
};

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

Changing color based on AngularJS condition using CSS

My HTML code looks like this: <div> <i class="glyphicon glyphicon-envelope" style="margin-top: -50px; cursor:pointer; color: #1F45FC" ng-click="createComment(set_id)"> </i> Route <center> ...

Is there a way to execute a code snippet just once when focusing on a specific field?

<form id="myForm"> <label for="fname">First name:</label><br> <input type="text" id="fname" name="fname"><br> <label for="mname">Middle name:</label> ...

Accessing JSON array values in a nested controller in AngularJS can be achieved by using

How can I access a Json array value in another controller? I am working with nested controllers where the nested controller should return the first character of the first name and last name. For example, if my first name is Anand Jee, it should return AJ. ...

transferring data between pages with ajax

I need to retrieve data from another page and display it on my current page using ajax. I have the following code snippet: <script> $(document).ready(function() { $(".link").on("click", function(e) { e.prevent ...

What is the best way to add data from an array to a DOM element in the same order it was retrieved from Firebase?

Utilizing Google Firebase Firestore for data storage and the Open Movie Database (OMD) in combination with Axios to retrieve movie information. I am currently developing a website that allows users to add movies to collections. On the collections page, al ...

When two divs are activated, the third div goes into invisible mode

I attempted this code, but it doesn't appear to be functioning correctly. if(div1)&& (div2)==display:none { div3=display:none; } else { div3=display:block; } ...

How to change class names dynamically in Vue.js?

I am looking for a way to dynamically change the background color based on a review rating using Vue.js. Ideally, I would like to achieve this with the following code: <div class="review" :style="reviewColor(hotel.average)"> In my methods section, ...

React ensures that the page is not rerendered until after data has been fetched

I am dealing with the following code snippet. This is my React hook: const [isLoading, setIsLoading] = React.useState(true); useEffect(() => { setIsLoading(() => true); // I expect the page to rerender and display loading now. const select ...

When the function is called, it will return the global `this

Attempting to bind the user object as 'this' and default time as the first parameter utilizing the function.call method let user = { name:'rifat', txt (time, msg){ console.log('['+time+ '] '+ this.name+ &apo ...

A unique feature where a bar emerges from the bottom of the screen, smoothly glides upwards, and then securely fastens to

I'm working on bringing to life a concept that I've been envisioning. The design would feature a long scrolling page with a unique navigation bar behavior. The idea is for the navigation bar to initially start at the bottom of the screen and the ...

Which is more recommended to use in AJAX (XMLHttpRequest) - eventListener or readyStateChange method?

As I revisited a video from WWDC12 discussing advanced effects with HTML5, I couldn't help but notice that for the demo they utilized req.addEventListener("load",callback,true) instead of the usual onreadystatechange. This made me wonder: what differ ...

Unable to locate 'react' for mdl module

Currently working on my first website using react, following a tutorial available at this link I am attempting to install and utilize the material lite module, but encounter a compilation error when starting npm with the following message: Error: Module ...

Solving issues with event handling through addEventListener within a functional component in React

I am working on a React component that includes an input field and I want to implement a character autocompletion feature. The idea is that when a user types " or ', the same character should be automatically added again, with the cursor placed i ...

How can you utilize jQuery to iterate through nested JSON and retrieve a specific matching index?

In the scenario where I have a nested JSON object like this: var library = { "Gold Rush": { "slides": ["Slide 1 Text","Slide 2 Text","Slide 3 Text","Slide 4 Text"], "bgs":["<img src='1.jpg' />","","<img src='2.j ...

vm.property compared to this.property

Although it may seem like a simple question, I am in need of some clarification. Currently, I have vuejs running on a single page of my website. The vm app is running in the footer script of the page without utilizing an app.js file or templates/components ...

Managing the undefined state on a kendo checkbox: Tips and tricks

Here's how I programmatically alter the state of a kendo treeview checkbox using the following code snippet: $(node).find('input[type="checkbox"]').prop("checked", !currentItem.checked); currentItem.checked = !currentItem.checked ...

Ways to keep track of Angular Watchers within a web page

Is there a reliable method to accurately count the number of watchers on a page? I have come across various articles that provide different ways to do it, but each gives me conflicting counts, making it difficult to determine the correct approach. A Stac ...

Ajax refreshes page to default state post search

I have implemented a live search feature that retrieves relevant information from the database and displays it in a table using Ajax to avoid page refresh. Currently, after each search, the results reset back to nothing until another input is received. How ...

Experiencing issues with AngularJS and jsFiddle - encountering strange error messages

Having trouble getting my jsFiddle to function properly. I keep encountering this error message along with a few others: Error in event handler for 'undefined': Error calling method on NPObject. Error: Error calling method on NPObject. at c ...

The THREE.TextureLoader() function will repeatedly load a single texture, potentially more than 20 times

An issue has been discovered with the THREE.TextureLoader() function, as it seems to load the same assets multiple times (often 20 times or more) in an unexpected and erroneous manner. The screenshot below from the browser console illustrates this behavio ...