AngularJS dynamic link

Could someone please help me with creating a conditional href instead of duplicating an a tag for hide/show functionality?

Here's the issue I'm facing: if DisplayLocation is null, I want to use the string "unknown", otherwise I want to display the location. I attempted something like x ? y : "unknown" but it doesn't seem to work in the href attribute.

<a class="btn-main orange" href="#!/movie-details/
   {{movie.Item.DisplayLocation | prettify}}/
   {{movie.Item.Title | prettify}}/{{movie.Item.Id}}" 
   id="view--{{$index}}"> View
</a>

Solution:

<a class="btn-main orange" data-ng-href="#!/movie-details/
   {{movie.Item.DisplayLocation ? 
       movie.Item.DisplayLocation : 'unknown' | prettify}}/
   {{movie.Item.JobTitle | prettify}}/
   {{movie.Item.Id}}" 
   id="view--{{$index}}">View
</a>

Answer №1

If you want to improve the organization of your code, consider creating a function within your controller that can be utilized in your data bindings.

Controller:

$scope.generateConditionalDisplayLocation = function generateConditionalDisplayLocationFn() {
    return $scope.movie.Item.DisplayLocation ? 
           $scope.movie.Item.DisplayLocation : "unknown";
}

HTML:

<a class="btn-main orange" 
   ng-href="#!/movie-details/{{generateConditionalDisplayLocation() | prettify}}/
   {{movie.Item.Title | prettify}}/{{movie.Item.Id}}" id="view--{{$index}}"> View
</a>

By moving this logic into the controller, you not only enhance the readability of your HTML but also keep your codebase cleaner and more maintainable!

UPDATE:

While using href is acceptable, there is a risk of users accessing an incomplete URL if Angular hasn't finished rendering the binding values. To mitigate this issue, it's recommended to use ng-href as suggested in Angular's documentation.

To implement this, simply modify your HTML code like so:

<a class="btn-main orange" ng-href="#!/movie-details/
   {{generateConditionalDisplayLocation() | prettify}}/
   {{movie.Item.Title | prettify}}/{{movie.Item.Id}}" 
   id="view--{{$index}}"> View
</a>

Answer №2

All content can be consolidated into a single expression, allowing filters to function as sub-expressions. This approach results in a more concise code with minimal impact on controllers:

<a class="btn-main orange" href="#!/movie-details/{{ !movie.Item.DisplayLocation ? 'unknown' : ((movie.Item.DisplayLocation | prettify) + '/' + (movie.Item.Title | prettify) + '/' + (movie.Item.Id)) }}" id="view--{{$index}}">View</a>

While the extra parentheses are not necessary, they enhance clarity. Furthermore, as noted by ryanyuyu, utilizing ng-href helps prevent any abrupt display of unparsed content.

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

Ensuring the validation of checkboxes using the Bootstrap framework

I am currently working on validating checkboxes using JavaScript. If the validation fails, I want to display a div with the class invalid-feedback below the checkboxes. However, when I add the invalid-feedback class to my div, it simply disappears. < ...

Implement a click event using jQuery specifically for Internet Explorer version 7

How can I add an onclick attribute using jQuery that is compatible with IE7? So far, the following code works in browsers other than IE8 and Mozilla: idLink = Removelst(); var newClick = new Function(idLink); $(test1).attr('onclick', null).clic ...

Guide to adjusting the color of Fluent UI icon when hovering with mouse?

I've been implementing Fluent UI in my current project. When initializing my button, I use this straightforward JavaScript code: iconProps: { iconName: 'NewFolder', styles: { root: { color: 'orang ...

Filtering data with AngularJS upon user clicks

Encountering a perplexing issue at the moment. I have created buttons using ng-repeat and my intention is for them to filter my list when clicked on. However, I am facing an issue where the list fails to filter upon clicking. Here are the buttons: <div ...

Accessing a JSON key using a JavaScript variable

Is there a way to dynamically replace the key "Argentina" in a JSON object with a javascript variable string? jQuery(document).ready(function() { $.getJSON('countries.json', function(data) { var output= data.Argentina[0].countryPho ...

Why is my jQuery + JSONP request not returning any data?

I'm having a strange issue with my script that is not returning any data from a JSON file sourced from a third-party site. Here's the code: $(document).ready(function() { var url = "http://konachan.net/post/index.json?limit=20&tags=hat ...

What is the best way to assign a variable with the type (x:number)=>{y:number,z:number}?

I am trying to initialize a variable called foo, but my current code is not compiling successfully. let foo: (x: number) => {y:number,z: number} = (x) => {x+1, x+2}; This results in the following error: Left side of comma operator is unused and ha ...

Tips for speeding up ngShow initialization and troubleshooting when ng-cloak doesn't work

I encountered a similar issue to the one described in this question, but none of the solutions provided worked for me. Here is a video showcasing my problem: https://www.youtube.com/watch?v=ByjmwmamemM Upon loading my app, multiple popovers with ng-show ...

Mastering the art of managing unchecked and checked checkboxes in Angular 2: A comprehensive guide

I have a code snippet where I want to display the initial state of checkboxes based on the 'initialstatus' array in the UI. I should be able to randomly change the status of any checkbox on the UI, and that change should also be reflected in the ...

Exploring Angular JS: the power of directives and making asynchronous calls

Recently, I started learning Angular and have come across an issue regarding Angular AJAX calls. I am facing difficulty with a service call that is triggered after my directive. I can't seem to make it work properly. The code functions fine with hard ...

Guide to creating the shared section of two wheels with CanvasRenderingContext2D

Is it possible to dynamically draw the shared area of two circular shapes using JavaScript and CanvasRenderingContext2D? My ultimate goal is to be able to adjust the size of the shape, ranging from a complete circle to a mere point. The desired outcome is ...

Steps for importing a JavaScript file from Landkit into a Vue project

Currently, I am working on an interesting project and utilizing Vue with Landkit Bootstrap. However, I am encountering issues with the JavaScript behavior of the Landkit component. I usually import the following links in my index.html file, but in the new ...

The hover effect generates a flickering sensation

I am having trouble displaying options on an image when hovering over it, as the displayed options keep flickering. $('a').hover(function(event) { var href = $(this).attr('href'); var top = $(this).next().css("bot ...

How to use Axios in Vue JS to access an array within a JSON object

Struggling to access arrays inside a JSON object and save them into separate arrays. Despite trying various methods, I have not been successful in retrieving these arrays. I suspect that my approach to accessing arrays within the JSON object is incorrect, ...

Using Angular JS to submit forms on a regular basis

My HTML form is set up within an Angular controller with inputs, action, and other elements already defined. The only issue I'm facing is that the form does not have a traditional submit button. Instead, there is a separate button on the page outside ...

Adding a new row to an existing formArray in Angular: A step-by-step guide

Can someone help me figure out how to add a new row and remove a row on this form? editCity() { this.form = this.fo'',))), recepieType: } createForm() { this.form = this.formBuilder.group({ }); } I am looking to implement ...

Django not receiving data from AJAX GET request

I am attempting to transmit data stored in localStorage through an AJAX GET request to Django, but the Django server does not seem to receive it. I have verified that there is data in localStorage("preselection") as indicated by the output of console.log. ...

The commitment to Q ensures that errors and exceptions are effectively communicated

Here is a code snippet that I am using to transform a traditional nodejs function into a promise-based one: Object.defineProperty(Function.prototype, "toPromise", { enumerable: false, configurable: false, writable: false, value: function ...

Transferring the input value to a different input field with Keyup in Angular 9

Is there a way to instantly pass data from one input field to another in Angular? I am facing some issues with this. How can I troubleshoot this problem? Component.ts export class AppComponent { number = ''; //initialized the text variable ...

Rendering with Next.js script

Within my Next.js project, there is a script implemented to render a widget. The code for this script looks like: <a className="e-widget no-button xdga generic-loader" href="https://example" rel="no ...