Dynamic AngularJS Content Loader

I am attempting to utilize angularJS in order to dynamically load content from my HTML using ajax calls. My goal is to create a single method that can handle different parameters to specify the ajax/REST uri and display the results in various components. Below is a snippet of the (non-functional) code I have been working on:

app.controller('ContentController', function($scope, $sce, $http) {
  $scope.FetchContent = function(pageId) {
    let contentUri = 'https://somewhere/restendpoint/?id=' + pageId;

    $http.get(contentUri).then(function(data) {
      return $sce.trustAsHtml(data.data.d[0].Content);
    }
  }
})
<div ng-controller="ContentController" class="row">
  <div class="col-md-4" ng-bind-html="FetchContent('home')"></div>
  <div class="col-md-4" ng-bind-html="FetchContent('welcome')"></div>
  <div class="col-md-4" ng-bind-html="FetchContent('contact')"></div>
</div>

However, this implementation is generating numerous ajax calls which is not ideal. I have tried creating a custom directive, but it updates all elements with the same data. Can anyone offer some guidance or advice on how to resolve this issue? Thank you!

Answer №1

After encountering repeated ajax calls, I found a solution using directives instead. This involved embedding element Ids to ensure each element is locked down:

app.controller('ContentController', function($scope, $sce, $http) {
  $scope.FetchContent = function(pageName, elem) {
    var contentUri = 'https://somecontent/restendpoint/?id=' + pageName;
    $http.get(contentUri).then(function (data) {
      $('#' + elem).html(data.data.d[0].HTMLContent);
    });
  }
});


app.directive('loadcontent', function($parse) {
  return {
    restrict: 'A',
    link: function ($scope, elem, attrs) {
      elem.ready(function() {
        $scope.$apply(function() {
          var func = $parse(attrs.loadcontent);
          func($scope, elem)
        });
      });
    }
  };
});
<div ng-controller="ContentController" class="row">
  <div class="col-md-4" id="e1" loadcontent="FetchContent('home', 'e1')"></div>
  <div class="col-md-4" id="e2" loadcontent="FetchContent('home', 'e2')"></div>
  <div class="col-md-4" id="e3" loadcontent="FetchContent('home', 'e3')"></div>
</div>

This method successfully inserts unique content into individual elements, but I can't help feeling there must be a more efficient way to achieve this. Any suggestions from experienced AngularJS users?

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

Three.js Collada Loader struggles to load a small scene with multiple objects

While I am new to Three.js, the question I have is quite complex. I am working with a Collada scene in DAE format, which actually includes references to other DAE files. The structure of this "parent" file looks something like this: <library_visual_sc ...

Include draggable functionality to a seating chart that is generated dynamically

I developed a function that generates table seats dynamically with equal spacing. The issue arises when I try to drag names from a list and drop them onto the seats as children. Unfortunately, I can't seem to achieve this functionality with the dynami ...

Accessing files from various directories within my project

I'm working on a project with 2 sources and I need to import a file from MyProject into nest-project-payment. Can you please guide me on how to do this? Here is the current file structure of my project: https://i.stack.imgur.com/KGKnp.png I attempt ...

Leveraging the OR operator in a ternary conditional statement

Trying to use a ternary operator to return null with two different strings, but it's not working as expected. Looking to achieve this: this.props.sportType === 'tennis' || 'soccer' ? null : <li onClick={this.props.onClick} clas ...

Having trouble with submitting an Ajax form to a MySQL database

My expertise lies in PHP and HTML, but I'm currently learning JavaScript. I'm facing a challenge with creating a form that can submit data to be inserted into MySQL without reloading the page (using AJAX). Here is the form I have: <form id=" ...

Error: The function expressJwt is not recognized as a valid middleware

As I delve into learning about middlewares, I encountered an issue when trying to import express-jwt. The syntax I used was: const expressJwt = require('express-jwt') To address the problem, I uninstalled the current version of express-jwt and i ...

Why is Joi validation triggering an error when dealing with a nested object? Could this issue be connected to the use of dot notation in the

I am facing an issue with my joi validation when trying to submit a form. The error message I receive is: STACK: Error: "author.surname" is not allowed at module.exports.citationJoi Upon reviewing my joiSchema, everything seems correct: const n ...

Unable to start dat.GUI in Three.js

After running my code, I encountered an error on this line: var gui = new dat.GUI(); The error message reads: 'Unable to get the 'getItem' property null reference or undefined.' Despite importing the necessary library, I am unsure of ...

Hash functionality does not cooperate with the back button, requiring the use of JavaScript to trigger a function when the URL changes

Hi everyone, I have a code snippet that is designed to read the value after the hash in the URL and display a specific div based on that value. It works as expected, except for when the hash is changed while already on the site or when navigating back with ...

Instructions for transferring an email attachment to a collaborative drive stored in a Google Sheets document

At the moment, I am utilizing a Google script that runs periodically on my Gmail account to retrieve all attachments labeled according to certain criteria. The issue arises when trying to access attachments within a folder located on a shared drive using t ...

Create a Bootstrap modal that includes a checkbox option to prevent it from appearing again in

I am attempting to display a bootstrap modal upon body load based on a value retrieved from a MySQL database. The bootstrap modal is included in the body and shown successfully depending on the database value using the following code snippet: $results ...

Enhance a portion of your text with some flair

Is it possible to apply styles to specific parts of text that are within an <input> value or a <span> element? For instance, I have the following data: {text text} an other text... I want to add styles to the text enclosed within {}. Here i ...

What strategies can be employed to streamline the code provided?

Can someone help simplify this JavaScript code for me? I would really appreciate it. Thank you! $(function() { $("#show1").click(function() { $("#showmore1").toggle(); }) $("#show2").click(function() { $("#showmore2").toggle(); ...

Error: The object "request" has not been defined. This issue occurs when trying to execute an Action

$dd = "<a href='javascript:void(0);' id='requestsend$send_id' onClick='request($send_id,request_send);' class='post-add-icon inline-items'><button type='button' style='background: #ccc;' ...

What is the reason behind the momentary functionality of v-for?

I'm facing a strange issue while working with Vue.js. I'm not sure if the problem lies with my code or if it's a bug in the framework. Here's the scenario: When I use v-for with a comma before it (v-bind), there are no errors but nothi ...

cutting tags with priority levels

I'm facing an issue where the vertical label "PINK" is centered perfectly in a section, but when I scroll down to the next section, it gets covered by a section with a higher z-index. div.back1 { background-color: #FF00FF; position: relativ ...

Encountering $stateChangeSuccess event twice

I am encountering an issue with an $http call within a function called getRoutes. This function is triggered whenever the state changes: $scope.$on('$stateChangeSuccess', function(event) { $scope.getRoutes($stateParams); }) Additionally ...

Separating express routes into individual files

After trying multiple solutions from Stack Overflow and various patterns for organizing routes in Node.js, I still can't seem to get it right. The endpoint either throws errors or returns a 404. Despite following suggestions from different sources lik ...

What is the best method for tallying the word count in a WYSIWYG editor using JavaScript?

I have been using a WYSIWYG editor to write and save my content. Now, I need to find out the number of characters I have written. For example, if I have written "My Count is 4", the count should be 13. Even if I format the text by making it bold or ital ...

Problem with resizing in CSS and jQuery

I need help creating a chatbox that can be resized. I've almost got it, but the bottom part of the chatbox detaches when I resize it. Also, I'm having trouble making the userList a fixed size that won't be affected by resizing. Check out th ...