Setting the ng-href attribute in Angular conditionally using a function

How can I dynamically set links in an angular controller based on a function's result?

<a ng-href="{{  setLink('contact') }}"

Inside the controller:

angular.module("my-app")
    .controller('navController', ['$scope', '$document', function($scope, $document) {
    $scope.page = $document[0].title;
    $scope.home = "My app";

    $scope.setLink = function(path) {
        return $scope.page == $scope.home ? 'views/' + path : path;
    }
}]);

I have been able to hardcode the urls like this:

<a ng-href="{{ page == home ? 'views/contact.html' : 'contact.html' }}"

Is there a way to pass a function as a parameter to ng-href?

Answer №1

It seems like your $scope.setLink function is not designed to handle any parameters, so the value you pass to it will not be returned as expected. You should update the function to accept a parameter for proper functionality.

$scope.setLink = function(path) {
    return $scope.page == $scope.home ? 'views/' + path : path;
}

Please review the following comment:

You may have missed closing brackets in your <a> tag, which could potentially create an issue. Please make the necessary correction:

<a ng-href="{{ setLink('contact') }}">Link Text</a>

Answer №2

the process functions as follows

angular.module("myApp", [])
.controller('mController', ['$scope', '$document', function($scope, $document) {
    $scope.page = $document[0].title;
    $scope.home = "My app";
    $scope.setLink = function(path) {
      url = $scope.page == $scope.home ? 'views/' + path : path;
      return url;
    };
  }]);
<script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d5b4bbb2a0b9b4a7fbbfa695e4fbe1fbad">[email protected]</a>" src="https://code.angularjs.org/1.4.9/angular.js" data-semver="1.4.9"></script>
    
<div ng-app="myApp" ng-controller="mController">
  <a ng-href="{{setLink('contact')}}">{{setLink('contact')}}</a>
</div>

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

obtain a jQuery element from a function

Can a function return a $ object, or does it need to be converted to a string before being returned? function returnObj() { obj = $("<img id='' src='' />"); return obj; } var obj = returnObj(); alert(obj); //returns [obj ...

What is the best way to implement sorting in a table using react virtualized?

I've been working on implementing sorting in my project using the table sorting demo available on Github. Here is the code I'm using: import React from 'react'; import PropTypes from 'prop-types'; import { Table, Column, Sor ...

How can we effectively translate intricate nested SQL relationships into manageable services using front-end data modeling best practices?

Seeking insights on potential solutions to a complex issue. Angular and Rails will be used, but this problem is more abstract and doesn't have to be addressed within these frameworks. What are the optimal methods for managing intricate nested SQL ass ...

repeated firing of keydown event in ReactJS

Having an issue with adding an event listener and checking if it's level 1. When I press the space key once, it seems to fire more than 50 times. Any assistance would be greatly appreciated. document.addEventListener("keyup", function(e) { if(l ...

Mastering the art of seamless navigation within a single page through the magic of

I have two HTML pages: "Login.html" and "index.html". Instead of a normal href linking, I want the user to navigate to "index.html" when they click on the login button. Furthermore, I want the index page to be displayed within the codes of login.html, cre ...

The occurrence of Multiple Button events leads to an error message stating: "Uncaught TypeError: Cannot read property 'remove' of undefined"

I am struggling to add an EventListener to each Delete Button (1,2,3) as I keep encountering an error that says "add" is undefined. Do you have any suggestions on how to fix this issue? My goal is to display a confirmation window when the DELETE button is ...

Transitioning from jQuery methodologies to AngularJS techniques

Currently, I am in the process of migrating a Jquery Ajax form to AngularJS and I've encountered a roadblock... The form I am working on contains multiple checkboxes grouped by categories. Some items are listed in more than one category, resulting in ...

The VueJS Hello world application is experiencing technical difficulties and is currently not functioning as

As a complete VueJS newbie, I've just started working on my very first app. It's supposed to be a simple Hello World application, but unfortunately, the code isn't quite behaving as expected :( HTML <!DOCTYPE html> <html lang=" ...

Conceal the excess content by placing it behind a series of stacked div

Within my layout, there is a fixed div called #navigation that houses buttons. Alongside this, there is scrollable content in the form of .card elements. The #navigation div currently displays with a green background for demonstration purposes, as shown b ...

Struggling with the conundrum of aligning a constantly changing element amid the

I was optimistic about the code I wrote, hoping it would work out in the end. However, it seems that my expectations might not be met. Allow me to provide some context before I pose my question. The animation I have created involves an SVG element resembl ...

What is the correct way to display the value "0" using ng-show?

Looking for a way to display a zero value in an Angular UI. <ng-show ng-show="item._source.change.backOrdered"><br> {{'pages.items.backOrdered' | translate}} {{item._source.change.backOrdered}}</ng-show> There are 2 scenarios ...

Update the Ngrx reducer when the component is present on the page

One dilemma I am facing involves managing two components within a page - an update user form and a history of events. Each component has its own reducer (user and events). My goal is to update the list of events in the store through an API call once the us ...

What are some methods for creating nested asynchronous calls in jQuery?

Here is an example in main.js: $.when( $.get('foo/bar.html'), $.get('lorem/ipsum.html') ).done(function(data1, data2){ someCode(); }); In lorem/ipsum.html: $.when( $.get('otherStuff.html'), $.get(' ...

Utilizing Angular routes within a Node.js application deployed on Heroku

I've been working on deploying an AngularJS project to Heroku. The app functions perfectly fine locally and when using heroku local web. However, upon attempting to access it, I encounter the error TypeError: response.sendFile is not a function. Ser ...

Having trouble retrieving data from JSON using JavaScript

Hey folks, I need some help with the following code snippet: function retrieveClientIP() { $.getJSON("http://192.168.127.2/getipclient.php?callback=?", function(json) { eval(json.ip); });} This function is used to fetch the IP address of visitors. When i ...

Identify the invalid field within an Angular form

After the form is rendered, I need to identify which fields are not valid after 5 seconds. Currently, I have a button that is set as ng-disabled="!step1Form.$valid". However, I would like to add a CSS class, possibly in red, to highlight the invalid fields ...

When attempting to submit form data, req.file returns as undefined

I'm currently facing an issue with my file upload functionality. I have a form that sends data to the controller in my routes file, but when the data is posted, the req.file appears as undefined. My goal is to upload the image to the public/images dir ...

Can a pledge be honored at a precise moment?

I have implemented transitions on my web page. When clicked, everything fades out to an opacity of 0 over a duration of 1 second. Then, a new page is swapped in and everything fades back in to an opacity of 1 over another 1-second duration. The issue aris ...

The error message "Uncaught (in promise) ReferenceError: dispatch is not defined" indicates that

Currently, I am utilizing vuex with index.js and auth.js stored in the store folder. My goal is to perform a basic sign-in operation within my signin.vue by calling an action from the store. However, I encountered the error 'Uncaught (in promise) Refe ...

VueJS encountered an insecure XMLHttpRequest endpoint during the request

I am currently working on a project that consists of a VueJs app with a Laravel backend serving as the API. While testing the app locally, everything works smoothly with the Https protocol. However, upon deploying it to the production server, I encountere ...