Prevent unauthorized access to ng-href by implementing validation measures in AngularJS

I have been struggling to find a solution for my AngularJS issue. As a newcomer to AngularJS, I am not yet familiar with all of its functionalities. I have a multi-part form that is submitted at the end using ng-href and HTTP GET. The code snippet for submission looks like this:

<a ng-href="#/report/{{ctrl.model}}" ng-click="ctrl.createReport()">Finish</a>

Now, I need to add validation to this form and prevent the link from being followed if the validation fails. The validation logic is in a controller function that returns true or false based on the result.

Unfortunately, I am working with code developed by someone else and I want to add validation without making significant changes. Is there a way to conditionally apply ng-href so that the browser follows the URL only if validation passes? If not, is there a way to programmatically perform the same GET request within the controller? I have explored options like $http.get() and $window.location.href, but they do not seem to fit what I need.

If you have any thoughts, ideas, or suggestions, please share them. Thank you!

Solution Used

HTML:

<a data-ng-click="ctrl.createReport()">Finish</a>

JS:

if (validate()) {
    $location.path('/report/' + angular.toJson(self.model, false));
}

Answer №1

Get rid of the ng-href completely and instead opt for the $location service.

function generateReport(){
    if(myForm.$valid){
        $location.path('/report'+model);
    }
}

Answer №2

Regrettably, this code snippet is part of a complex implementation created by another individual. My goal is to introduce the validation aspect without making extensive modifications to the existing logic.

Here's a workaround for you. This directive intercepts the click action if the specified expression evaluates to false. As a result, the browser does not follow the href link and ng-click event is also prevented from executing.

javascript

module.directive('eatClickIf', ['$parse', '$rootScope',
  function($parse, $rootScope) {
    return {
      // Ensure that eatClickIf is compiled before ngClick and ngHref
      priority: 100,
      restrict: 'A',
      compile: function($element, attr) {
        var fn = $parse(attr.eatClickIf);
        return {
          pre: function link(scope, element) {
            var eventName = 'click';
            element.on(eventName, function(event) {
              var callback = function() {
                if (fn(scope, {$event: event})) {
                  // Prevent execution of ng-click
                  event.stopImmediatePropagation();
                  // Prevent following the href link 
                  event.preventDefault();
                  return false;
                }
              };
              if ($rootScope.$$phase) {
                scope.$evalAsync(callback);
              } else {
                scope.$apply(callback);
              }
            });
          },
          post: function() {}
        }
      }
    }
  }
]);

html

<a ng-href="#/report/{{ctrl.model}}" 
   ng-click="ctrl.createReport()" 
   eat-click-if="!ctrl.modelIsValid()">Finish</a>

Answer №3

My recommendation is to eliminate the ng-href value and modify the path from the JavaScript condition using $location

<a ng-href="" ng-click="ctrl.createReport()">Finish</a>

Add the $location service and execute:

$location.path('/newValue')

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

How can I choose an expandable element using Selenium?

I am currently facing issues while trying to select an element on a webpage using selenium. The element in question is expandable, and when clicked, it reveals other items/fields. Here is the code snippet for the element: <DIV class="section"> ...

Tips for refreshing the ion-page following a pop() action in Ionic 2

On my website, I have a total of 2 pages - Page1 and Page2. During navigation from Page2 back to Page1, I use the method this.nav.pop() to close Page2 and return to Page1. However, I am looking for a way to refresh Page1 after returning to it. Any help ...

Storing video blobs in the filesystem using Electron and Node.js

My electron application allows users to record video from their webcam using the MediaRecorder API. After hitting the "stop record" button, I am able to obtain a blob of the recorded video. I am trying to figure out how to convert this blob into a real w ...

Embrace the D3js Force Layout barrier and dive right in

Currently, I am working on a force layout project. My main objective is to enable the nodes to avoid a particular div element placed in the center without utilizing gravity within the SVG. I have already implemented collision detection and bounding within ...

Exploring the boundaries of HTML data manipulation using JavaScript or jQuery

In my HTML (within a Twig template), there is the following code snippet: <li id="{{folder.id}}" data-jstree='{"icon":"glyphicon glyphicon-tags", "type":"folder"}' ><a href="#">{{folder.name}}</a> I'm attempting to extrac ...

Attempting to forward an image in a node-js/express application

I am facing an issue with a broken image link when trying to access it through Express: app.get('/fileThumbnail', function(req, res) { var url = proxiedURL +"?" + querystring.stringify(req.query); logger.info('/fileThumbnail going to url& ...

How can I collapse the dropdown menu in typeahead.js?

I am currently utilizing typeahead.js for a typeahead functionality. My goal is to achieve the opposite of what was discussed in this thread: Programmatically triggering typeahead.js result display Despite attempting to trigger a blur event on the typeah ...

Tips for Making Changes to a Polyline on Google Maps

I am currently utilizing the Directions Service provided by Google Maps V3 API, and I have a specific requirement to shorten the length of one of the steps by 1 meter (let's assume it's the final step). Issue: The directionResult can be viewed h ...

Do we need to use the render method in ReactJs?

I'm curious about how ReactJs uses its Render() functionality. Let's say we have some HTML code within index.html: <section id="Hello"> <h1>Hello world</h1> <p>Something something Darkside</p> </section&g ...

Dealing with Errors in AngularJS $resource Using Callbacks

I have a factory that offers various services for fetching data from a custom API I created. All the callbacks are functioning correctly, but I am interested in implementing error handling during the fetch process. .factory('customApiService', f ...

How to Implement Flexbox Display Across Various Browsers Using jQuery?

Running into an issue here. I'm trying to switch from display: none to display: flex, display: flex-box, and display: -ms-flexbox but for some reason it's causing errors in my code.. Here's what I've been working on: $(elem).css({&apos ...

Ensure that the input button for uploading is only accessible when checked and is marked as

Most of my previous questions have been about input boxes and SQL, as I am still in the learning process. Any help is greatly appreciated. My current question revolves around displaying a button to upload an image using PHP (although for this example, I w ...

Transferring PHP Arrays to JavaScript with JQuery

I am facing an issue with redrawing markers (on Google Maps) from a database using jQuery form. Here is the code snippet: Index.html: var map; var data; function updateLocations(){ var post= $.post('php/getLoc.php',{table: "Auto"), functio ...

Vue table displaying a list of books with a button that allows users to easily send the title of the

Hey everyone, I am new to Vue and struggling with a certain task. I have two tables: Books and Booking. Books: ID, NAME, AUTHOR etc. Booking: ID, ID_USER, ID_BOOK I'm creating a page in Vue that displays all bookings, but the table only shows the BOO ...

"Changing a Java script base addon file to a customized addon in Odoo 16: A step-by-step guide

Here is the JavaScript file located in the "documents" enterprise base addon: I want to include the field "document_type_id" in the export const inspectorFields = [] array through a custom addon. /** @odoo-module **/ import { device } from "web.confi ...

Upon initial load, the masonry elements on the webpage collapse unexpectedly

Hey there! I'm currently in the process of creating my own personal website - an online portfolio. While this is my first attempt at building a website from scratch, I must admit that I am quite new to HTML, CSS, JavaScript, and PHP. In fact, my know ...

Tips for ensuring a synchronous `setState` in React following an axios response

When making HTTP requests with axios, I encounter an issue where setState is happening before pushing the data to the 'orders' Array. This results in the data not being printed in the correct way. Using SetTimeout as a workaround works, but I wan ...

Is React.js susceptible to XSS attacks through href attributes?

When user-generated links in an href tag appear as: javascript:(() => {alert('MALICIOUS CODE running on your browser')})(); This code was injected via an input field on a page that neglects to verify if URLs begin with http / https. Subseque ...

Cease operation once the data has been written to a text file using fs.writeFile

Below is the Node.JS code using Express that I have implemented: let app = express(); app.use(cors()); app.get('/callback', function (req, res) { // Your application requests refresh and access tokens // after checking the state parame ...

The communication between socket.io encountered a net::ERR_SSL_PROTOCOL_ERROR

Here is the client code I am using: const socket = io(url); And this is the server code running on a Linux server with Express: const server = require("http").createServer(app); However, when I attempt to establish a connection, an error occurs. https:/ ...