In Angular, is there a way to concatenate a variable with "blah" at the beginning and end?

Success! Check out this snippet:

<div ng-include="'/partials/' + items.my_filename + '.html'"></div>

Despite finding the file, an error is still thrown:

GET http://localhost:9000/partials/.html 404 (Not Found) 

Any ideas on how to eliminate this error?

UPDATE: The variable is retrieved from a remote database. Could this delay be the culprit?

UPDATE2: Confirming the delay is the issue. Seems like a question for Firebase.

Answer №1

To achieve conditional rendering, implement ng-if

<div ng-if="items.my_filename" ng-include="'/partials/' + items.my_filename + '.html'"></div>

For instance, see the difference in behavior between using with ng-if: http://jsfiddle.net/TheSharpieOne/daFhp/1/ Only one call is made, with the specified file name (if available).

Compare this to using without ng-if: http://jsfiddle.net/TheSharpieOne/daFhp/ Notice the redundant calls, one without the variable/file name and one with the file name (if available).

The inclusion of $timeout in the examples is to mimic delays in AJAX requests.

ng-if aids in avoiding unnecessary calls to the server.

UPDATE
In newer AngularJS versions (1.2.0-rc3+), having both ng-if and ng-include on the same element may cause issues. To resolve this, wrap the ng-include element within an element featuring ng-if.

<div ng-if="items.my_filename">
    <div ng-include="'/partials/' + items.my_filename + '.html'"></div>
</div>

Answer №2

To take advantage of the fact that ng-include won't do anything with a null argument, you can use the following approach:

For example, you can do this:

<div ng-include="partialPath"></div>

By setting partialPath to null initially and updating it after an HTTP request:

app.controller('Ctrl', function ($scope, $http) {
  $scope.partialPath = null;

  $http.get(...).success(function (data) {
     $scope.partialPath = '/partials/' + data.my_filename + '.html';
  });
});

Alternatively, you can also use a filter for better reusability:

app.filter('partialize', function () {
  return function (name) {
    return name ? '/partials/' + name + '.html' : null;
  };
});

And then include the partial like this:

<div ng-include="my_filename | partialize"></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

changing web pages into PDF format

I need to convert HTML to PDF on a Linux system and integrate this functionality into a web application. Can you suggest any tools that are capable of doing this? Are there any other tools I should consider for this task? So far, I have attempted the foll ...

Adjust the height of images to be consistent

I'm currently working on creating a grid layout with 4 images in a row using DaisyUI card component. However, I've run into an issue where there is white space at the bottom of some images due to varying image heights. Is there a solution that wo ...

Enhance the functionality of Map.set by automatically storing the new entry on the disk as well

This code is intended for development purposes only, to resume work from where I left off when restarting the local server. I aim to avoid modifying the production code in any way. My goal is to save new entries to disk when using map.set(...). Below is a ...

Unable to retrieve the user ID from a Discord username using Discord JS

let string = `${args[1]} ${args[2]}` console.log(string) const idofuser = client.users.cache.find((u) => u.username === `${string}`).id I am facing an issue with DiscordJS where it says "cannot read property 'id' of undefined" when trying to ...

How can I retrieve a DOM object following an AJAX request?

My AJAX call fetches and appends HTML content to the current page. I hope to access this newly added HTML using standard jQuery selectors. Here's my desired approach... $.ajax({ url: url, success: function(data) { $('body').app ...

Implementing socket.io in a node.js server with express to showcase a welcome message upon user login

Currently, I am in the process of creating a web chat client using socket.io. However, before I can proceed with this project, I need to establish communication between my server and the website on localhost. Despite receiving the 'listening' me ...

How can I resolve the Error: Element type is invalid?

https://i.sstatic.net/9PehR.jpgI am encountering the error message displayed above, and I am uncertain about the cause of this issue. In the code snippet below, I am fetching data from a file named Data.js located in my root folder. When I run the app, I r ...

Issue with JQuery Each function not waiting for the inner function to complete

When I have this section inside an ajax function $.each(data['Result'][0], function(Key, Value) { InputGen(Value['Type'], Value['Name'], Value['Other'], Value['Value'], function(Html){ Table = ...

AngularJS select box setting selected valueIt can be accomplished by manipulating the

I am facing an issue with a selectbox populated with options from the backend. <tr> <td class="col-lg-4">Superkund</td> <td><select class="form-control input-sm2" ng-model="selectedSupercustomer" ng-options="item as item ...

The next/font feature functions perfectly in all areas except for a single specific component

New Experience with Next.js and Tailwind CSS Exploring the next/font Package Delving into the realm of the new next/font package has been quite interesting. Following the tutorial provided by Next.js made the setup process smooth sailing. I've incorp ...

What is the best way to set jade as a global variable in a node.js Express application?

Currently, the routing function shown below is operational: exports.summary = function(req, res, next) { var jade = require('jade'); res.render('myView', { main: jade.renderFile('./views/summary.jade') }); }; The ...

Querying a list of objects with nested pointers using the Parse.com Javascript API

How can I efficiently query my Parse.com backend for a list of objects that contain specific pointers within them? For example, if ObjectA contains a list of pointers to ObjectB, how can I query for all ObjectA's that have ObjectB in their list? I a ...

The process of altering a property in input data within Vue.js

I have a component called Input.vue that displays a label and an input field of some type. Here is how it looks: <template> <div class="form-element"> <label :for="inputId" :class="['form-element-tit ...

Building a div element within a React function

For an exercise, I need to create an input field and a button. The goal is to display the text from the input field in a div/span below when the button is clicked. If I change the text in the input field and click the button again, the displayed text shoul ...

Problem with Custom MUI fields not detecting value change

I want to make custom form components so I don't have to update each item individually if I want to change the style. The ReportSelect component doesn't update the value when a menu item is selected, and the ReportTextField only works for the fir ...

Issues arise with the blinking of my table rows

I'm working on a page with a table where certain rows need to blink under specific conditions. This page is a partial view that I load using the setInterval function. However, I've encountered an issue where the blinking functionality goes hayw ...

Executing the AngularJS nested controller only once

I am still new to Angularjs and just started working on an app that has several "projects" each with a local menu displayed on specific pages. The main navbar with footer is located in the Index.html: <body ng-app="ysi-app" ng-controller="MainControlle ...

Property-based Angular Material row grouping in a mat-table is a powerful feature that enhances

Is there a way to organize the data in one row with the same ID? Currently, my data looks like this: Data Set: { "id": "700", "desc": "Tempo", "richiesta": "20220087", "dataElab": &quo ...

The issue of selecting multiple classes simultaneously is not being resolved

Here is my JavaScript code snippet: $('.normal-box').click(function(){ //unique row id var id = $(this).data('row-id'); //its index according to the content array var index = $(this).data('index'); //which car ...

jQuery replacement for replaceChild method

I've been attempting to swap out an existing DOM element with a new one that I created. I attempted the following code snippet: $(this).parent().replaceChild(newElem,this); However, it resulted in an error message saying $(this).parent().replaceChi ...