Loading templates (partials) in Angular.js on the fly

Is there a way to dynamically load templates into an Angular app based on a parameter within a ng-foreach loop?

<body ng-app="MyApp" ng-controller="ExampleController as example">
   <div  ng-repeat="item in example.items" class="someClass" ng-switch="item.type">
      <!-- Load different templates depending on the value of item.type -->
   </div>
</body>

Check out this Fiddle for reference: https://jsfiddle.net/rsvmar2n/1/

Any suggestions on how to achieve this? I tried using ng-switch: https://jsfiddle.net/rsvmar2n/6/

I'm looking for a more efficient, "angular" approach to implementing this feature.

Edit: Ideally, I would like to avoid making an http request for every partial template that is loaded (as in the case of ngInclude).

Edit2: Ultimately decided to use ng-include along with cached templates. Check out the updated Fiddle here: https://jsfiddle.net/rsvmar2n/24/

Answer №1

If you want to optimize performance by using cached templates in ng-include, you can create a function that returns the id of the template. An illustrative example demonstrates how this can be implemented.

The controller function handling the template could resemble:

$scope.getTemplate = function(item) {
    switch(item.type)
  {
    case "type1":
        return 'testtype1.html';
    default:
        return 'testtype2.html';
  }
}

Here is an example of the html structure:

<script type="text/ng-template" id="testtype1.html">
  <p>This is the template 1</p>
</script>

<script type="text/ng-template" id="testtype2.html">
  <p>This is the template 2</p>
</script>

<body ng-app="MyApp" ng-controller="ExampleController">
  <div ng-repeat="item in items" class="someClass">
    <!-- Load different templates based on item.type -->
    <div ng-include="getTemplate(item)"></div>
  </div>
</body>

Answer №2

To implement this functionality, you can define a custom directive like so:

app.directive('myCustomDirective', function(){
  return {
    restrict: 'E',
    scope: {item: '=item'},
    templateUrl: function(element, attrs){
      if (!attrs.type) return 'default.html';
      return attrs.type + '.html';
    }
  } 
});

This will allow you to create different templates such as type1.html, type2.html, etc.

In your controller, simply use the directive like this:

<my-custom-directive ng-repeat="item in items" item="item", type="item.type">

Answer №3

By utilizing ng-include, you can conveniently allocate the source dynamically - for instance, in your main template:

<div ng-include src="templateName"></div>

Here, templateName corresponds to a variable name in your controller.

$scope.templateName = 'path/to/your/template.html';

Any modifications to this value during a digest cycle will automatically update the displayed content.

Answer №4

By using different conditions, you have the option to load either single or multiple templates.

Utilize ng-switch

ng-if="item.type=='type2'||item.type=='type3'"

LoadMultipleTemplate for loading multiple templates based on your selections.

LoadSingleTemplate to load a single template.

Edit

Using ng-include, dynamic views can be loaded.

In the provided example, there are no specific conditions set. However, it is possible to add another ng-repeat within ng-repeat and perform actions based on the inner loop. Make sure to structure the JSON object accordingly for the inner ng-repeat.

loadViews

<div  ng-repeat="item in example.items" class="someClass" >

         <ng-include src="item.type + '.html'">{{item.type}}</ng-include>

</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

How does Chrome have the capability to access the gist json file? Isn't that typically not allowed?

Fetching a JSON file from Github Gist can sometimes be straightforward, but in certain situations, I have faced difficulties due to CORS restrictions. This has led me to resort to using JSONP instead. Can you shed some light on why this is the case? ...

VS Code lacks autocomplete intellisense for Cypress

I am currently using Cypress version 12.17.1 on VS Code within the Windows 10 operating system. My goal is to write Cypress code in Visual Studio Code, but encountered an issue where the cypress commands that start with cy are not appearing as auto-comple ...

Utilizing withRouter outside a component to navigate through historical data

I'm still getting the hang of react router and encountering some challenges. I can easily use history within a component without any issues. However, when trying to access history from a function outside the component, I run into problems. Despite my ...

A method for highlighting duplicate rows in a DataTable by formatting them with the same color

I am currently utilizing the DataTable plugin to display rows in a table. I would like to highlight duplicate rows in the same color scheme. Can someone please assist me with this issue? In the example below, the entry for Black Winters is duplicated. I ai ...

Troubleshooting ng-class functionality in AngularJS

I am attempting to utilize AngularJS in order to change the class name of a div element. Despite following the guidance provided in this answer, I am encountering difficulties as the class name is not updating in my view. Below is the code from my view: ...

What is the best way to create a JavaScript "input" field that only accepts vowel letters?

Is there a way to create an "input" field that only accepts vowel letters? Additionally, I want to ensure that copying and dragging text into the input field will also be filtered out. <div class="field"> <input class="fie ...

"Enhance your HTML table by selecting and copying cell values with a simple click and CTRL +

I stumbled upon a fantastic script for highlighting HTML table rows and it's working perfectly: I decided to modify the onclick event to onmouseover and included additional code to select a cell by clicking on it. Now I can select, check which one is ...

What is the process for inserting a scroll bar within a div element?

   I have recently created a webpage using some divs, along with a bit of CSS and JavaScript. I am struggling to figure out how to add a scrollbar to one of my divs. The code is not overly complex, as it includes both CSS and JavaScript. <html> & ...

Step-by-step guide on duplicating a div a set number of times

I am looking to replicate the entire div multiple times (e.g., on an A4 paper, top left corner, top right corner, bottom left corner, and bottom right corner). <script language="javascript" type='text/javascript'> function updateD ...

Is there an improved method for toggling animations in CSS using jQuery compared to my current approach?

Looking to create a toggle effect for a dropdown box that appears and disappears when a button is clicked. var clickState = false; $("#show").on("click", function() { if (!clickState) { $(".animated").removeClass("off"); refreshElement($(".an ...

Guide on retrieving file information after transmitting it to another PHP file through Ajax

I have written code to upload a file and send it to a php page. I would like the response to be an array containing information about the uploaded file such as name, size, type, etc. I am using the "POST" method for uploading the file. Is this approach cor ...

Is it possible for data passed through props on Vue.js router-view to be visible in browser developer tools?

I have passed several props to the router-view component in this manner: <router-view :zipchange="zipchange" :accountitems="accountitems" :accountloaded="accountloaded" :profilepic="profilepic" /> Upon inspecting an element in the browser's de ...

Designing an architecture for a Java, Android, and database application - what will the final app's appearance be

I am currently working on a website where users need to complete tasks using an Android device: Fill out a simple HTML document. Sign the document on their Android device. Save the data entered into a database on the website. Some key points to consider ...

Unable to observe the transition of opacity changes in threeJS for tweens

<script type="importmap"> { "imports": { "three": "https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f2869a809797b284c2dcc3c4c0dcc2">[email protected]& ...

Delete any HTML content dynamically appended by AJAX requests

I'm currently working on a page dedicated to building orders, where the functionality is fully dependent on ajax for finding products and adding them dynamically. However, I encountered an issue when attempting to remove an item that was added via aj ...

Issue with Component: Data is not being injected into controller from ui-router resolve, resulting in undefined data

Encountering an issue with resolve when using a component and ui-router: the data returned after resolving the promise is displaying as "undefined" in the controller. Service: class userService { constructor ($http, ConfigService, authService) { th ...

Exploring nested elements in MongoDB with the help of Node.js API

In my current Node.JS API, I have a function written like this: Board.find({ users : req.user._id}) This function is designed to find all documents where the user's id is inside the array named users. For example, it will successfully fin ...

In JavaScript, filter out an array of image links that end with .jpg, .jpeg, .png, or

Need assistance, could someone lend a hand? I've got an array of image URLs and I'm attempting to filter out only the links with supported images using regex or endsWith(). It's been a struggle all morning. Appreciate any help offered! ...

What is the process for making a custom texture map to use in ThreeJS materials?

Recently, I acquired a fbx model that utilizes a UV map to efficiently texture the model. The model is composed of a single mesh that needs to be colored using 4 quadrants as shown in the image below: https://i.sstatic.net/RR6m3.png To achieve this color ...

Activate on-demand static regeneration with Next.js

I am thoroughly impressed by the functionality of Incremental Static Regeneration in Next.js. However, I am currently seeking a method to manually trigger static page regeneration as needed. It would be ideal to have a command that can be executed via an ...