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

What is the best way to save a jQuery or JavaScript variable into a JSON file?

Is there a way to save a jquery variable in a json file? I have the following: var image='/test/test.png'; I am obtaining this path through file upload: <input type="file" name="imageurl" value="imagefile"></input> Therefore, I ne ...

The most efficient method for retrieving data in React

Recently, I started working on a React App integrated with Riot API to display users' recent games and more. As part of this project, I'm utilizing React and NextJS (fairly new to NextJS). However, I'm contemplating the most efficient way to ...

Enhance User Experience with the Tooltip Feature and Customized

Here is the jQuery code I am using to style my tooltips: $(function() { // select all input fields within #tooltips and attach tooltips to them $("#tooltips :input").tooltip({ // place tooltip on the right edge position: "cen ...

You can obtain the values of multiple div selections using jQuery

In a display with two columns, I want to be able to perform a common operation (such as delete) based on the selection of certain div IDs. If a user selects the div IDs participant_1, participant_4, participant_6 at the same time, I need to collect these ...

Enhancing your website's design with dynamic CSS variables using JavaScript

Is there a way to update CSS variables specifically scoped under a certain CSS class (or even other complex CSS selectors) that are predefined in a stylesheet? This question extends beyond just CSS variables and includes other CSS properties as well, quest ...

JQuery cannot target content that is dynamically inserted through an Ajax request

When I use an ajax call to pass dynamically generated html, such as in the example below: var loadContent = function(){ $.ajax({ url: '/url', method: 'GET' }).success(function (html) { $('.con ...

Adding or removing a class using Jquery based on the condition of form validation

I am facing a problem with the following code that adds and removes classes to bring the next stage of the form. The form progresses step by step where certain fields need to be filled before validation on the next button, followed by filling other fields. ...

Unraveling the mysteries of this PHP-generated object

Need help with iterating over a JSON object generated by PHP code in response to a web service request. Looking for guidance on rendering sub-objects in a select list, especially those with value indexes. Can someone provide assistance on populating a sel ...

Adjust the translateX value and element size based on either the parent element's size or the window's dimensions

Is this question specific enough to relate to others' problems? My issue involves two elements, a child and a parent, with the child element rotating around the parent using CSS animations. <div class="planet"> <div class="moon"></di ...

Implementing AngularJS ng-click to dynamically add a duplicate Div or Widget with every click

The code below showcases a series of divs displayed one after the other: <ul class="record"> <li id="{{record.id}}" ng-repeat="record in records"> <div> Widget Code.... </div> </li> </ul> In addition to th ...

Move the accordion slider to the top of the browser

I'm working with an accordion menu that has some long content. To make it more user-friendly, I want to add a slide effect when the accordion items are opened. Right now, if you open the first two menu items, the last item's content is cut off a ...

One question I have is how I can successfully send a value within the RxJS subscribe function

I am currently in the process of transitioning the code to rxjs Here is my original code snippet. userAuth$: BehaviorSubject<ArticleInfoRes>; async loadArticleList(articleId: number) { try { const data = await this.articleApi.loadArticl ...

Unable to get $scope.$on to function correctly within Jasmine SpecRunner

Recently, I've delved into using Jasmine to test an AngularJS application. I'm fairly confident that I've imported all the necessary components in the SpecRunner file, but I keep encountering this error: TypeError: $scope.$on is not a funct ...

What are the steps to configure ESlint and Prettier with the Airbnb style guide for a React Native/JavaScript project (Expo) in VS Code?

I have looked through numerous tutorials on this topic, but I haven't been able to get it to work. In the tutorials, when you run npm install eslint, it usually prompts you in the command line about using a popular style guide. However, this no longer ...

Modifying the input's value dynamically alters the selection choices in Vuetify

Choose the First option Fpo, when you select the first item, the first object in the list is assigned to the variable test. I have used test.name as a model for that input field. Strangely, when I try to modify the input field, the select option also chang ...

Can Angular components be used to replace a segment of a string?

Looking to integrate a tag system in Angular similar to Instagram or Twitter. Unsure of the correct approach for this task. Consider a string like: Hello #xyz how are you doing?. I aim to replace #xyz with <tag-component [input]="xyz">&l ...

Creating PopUp Windows with PHP and JavaScript

There is a function created on my page that opens a pop-up window when clicking on a game-mod name: <SCRIPT language="javascript" type="text/javascript"> function popModData( modName ) { var url = "./modList.php?mod=" + modName; ...

"Troubleshooting issue: Unable to retrieve grid data from Google Sheets API v4 when integrated

I've implemented a function within a React component that retrieves JSON data from an API request and logs it: async function getAllSheets() { let response; try { response = await window.gapi.client.sheets.spreadsheets.values.batchGet( ...

Understanding the moment when the DOM is fully rendered within a controller

I'm currently facing an issue with AngularJS. In my controller, I have a $watch setup like this: function MyController() { $watch('myModel', function() { $rootScope.$emit('do-oper'); }); } The value of 'myMod ...

Running a node.js project on the client side without using npm for deployment

Looking for a solution to efficiently deploy my nodejs project with frequent updates. The site does not have npm available, so I have to package the node_modules every time, which results in a large file size (80MB) that takes a long time to send via ftp t ...