Is there a way to dynamically assign ng-include or ng-controller in Angular JS?

I'm a beginner with Angular JS and after some research, it seems like what I want to achieve might not be possible. However, I'd like to explore if there is an alternative solution that can provide a similar outcome.

My goal is to populate a page using data from a JSON file, and dynamically load a customized list item using the URL specified in that JSON file. Here's an example:

JSON (inside controller):

function ExCtrl($scope) {

    $scope.examples = [
            {name:"example", 
            num: 1, 
            url:"website.html"}
        ];
    }

JS (inside HTML):

<ul ng-controller="ExCtrl">
   <li ng-repeat="example in examples">
      <div ng-include src="folder/{{example.url}}> </div>
   </li>
</ul> 

Solution :

<ul ng-controller="ExCtrl">
   <li ng-repeat="example in examples">
      <div ng-include src="example.url"> </div>
   </li>
</ul> 

Current code snippet:

function ExCtrl($scope) {

    $scope.examples = [
            {name:"example", 
            num: 1, 
            url:"folder/website.html"}
        ];
    }

Answer №1

According to the provided documentation:

ngInclude|src{string} – angular expression that evaluates to a URL. If the source is a string constant, ensure it is enclosed in quotes, for example: src="'myPartialTemplate.html'".

In this scenario, it is recommended to configure a custom ngResource. Within the controller, inject the resource and retrieve the JSON data, then assign it to a scope variable.

angular.module("foo", "ngResource")

  .factory("ResourceType", function($resource){
    return $resource("/resourcetype/:id", {id: "@id"}, { "update": {method:"PUT"}});
  })
  .controller("ExCtrl" function($scope, ResourceType){
    $scope.examples = ResourceType.query();  
  });

You can then define your ng-include URL while iterating over your resource.

Additionally, avoid using {{}} around your variable names.

UPDATE:

I intended to provide you with a Plunker demonstration, but there seems to be an issue. Instead, here is an inline example that accomplishes what you are seeking. To enhance clarity, I have omitted the resource aspect. You may wish to reintegrate it when fetching the JSON remotely.

<!DOCTYPE html>
<html ng-app="angularjs-starter">

  <head lang="en">
    <meta charset="utf-8">
    <title>Custom Plunker</title>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <ul ng-controller="MainCtrl">
      <li ng-repeat="example in examples">
        If {{example.url}} were valid, it would load in the div. 
        <div ng-include="example.url"> </div>
      </li>
    </ul> 
  </body>
</html>

var app = angular.module('angularjs-starter', []);

app.controller('MainCtrl', function($scope) {
  $scope.examples = [
     {name:"example", 
      num: 1, 
      url:"example.html"}
  ];
});

Update: Plunk

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

Achieving the new value without retrieving the old value in a jQuery on('save') event

I am currently utilizing X-editable and attempting to retrieve the value of an element when a user changes it. However, I am encountering difficulties as I am only getting the previous value instead of the changed value. For example, if the original value ...

Why am I seeing back-end console errors that are related to my front-end?

Recently, I encountered an error message that prevents me from using 'import' in my front end code when trying to execute 'node index'. This issue never occurred before, and it only arose when I returned to this project. In my backend ...

Creating dirty or touched input programmatically in Angular2 can be achieved by using the `.markAsT

Looking to integrate a JQuery plugin with Angular2? Essentially, this plugin generates a duplicate of specific HTML content containing inputs. As data is modified, Angular2 automatically re-renders the content along with any errors. However, the challenge ...

Issue with the Release build failure involving the Linker and ___gxx_personality_v0"

In my pursuit of running my application offline on my phone using react-native v0.40, I attempted creating a Release build. Unfortunately, this resulted in errors causing the app to fail starting on my phone (although it runs successfully on the simulator) ...

Retrieving information from various object keys using Vue.js

Currently, I am in the process of setting up a feature in my application where users can select an option from a list and the background of the app will change based on their selection. Imagine having a list structured like this: <li v-for="item in it ...

Successive Node.js Post Requests

Is it possible to make consecutive POST requests in separate route files and redirect to a different EJS page with each request? Here is my file structure: Routes: index.js - users.js - users1.js Views: index.ejs - users.ejs - users1.ejs This is my ...

``There seems to be a problem with the ngb time picker when using the up and

Currently, I am utilizing Bootstrap 4 and NG Bootstrap time picker for a project in Angular 10. Despite correctly adding all the code, I have encountered an issue where the up and down arrows on the time picker are not functioning as expected. Below is a s ...

Strange error message regarding ES6 promises that is difficult to interpret

Snippet getToken(authCode: string): Promise<Token> { return fetch(tokenUrl, { method: "POST" }).then(res => res.json()).then(json => { if (json["error"]) { return Promise.reject(json); } return new Token ...

Tips on positioning a div based on the screen dimensions

In my table, there is an icon that reveals a chart as a popup when hovered over. This div is where the chart is displayed: <div id="chart-outer" style="@style" class="popup-chart close"> <h2 id="charttitle&q ...

When attempting to register a custom Gamepad class using GamepadEvent, the conversion of the value to 'Gamepad' has failed

I have been working on developing a virtual controller in the form of a Gamepad class and registering it. Currently, my implementation is essentially a duplicate of the existing Gamepad class: class CustomController { readonly axes: ReadonlyArray<nu ...

I struggled to properly parse JSON data from the internet

I've developed a basic Android app for JSON parsing. I attempted to parse JSON data from a webservice URL and display it in a listView, but for some reason, it's not functioning properly. Below is the code that I tried. Main.java package com.ex ...

Creating a jQuery thousands separator without losing the decimal accuracy with .toFixed(2)

I'm currently working on a Wordpress project where I need to create a pricing table using jQuery. One of the specific requirements is to format the numbers in thousands with spaces, like converting 1000 to 1 000. Although I have attempted various jQu ...

Is it possible to assign variables inside an http call from a function in AngularJS?

Seeking urgent assistance. I need help with a function that resembles the following: $scope.getData = function(id) { $http.get('/url' + id).success(function (data) { return data.a.b.c; }); }; In another function, I have the fol ...

What could be causing my click event to fail to register after sorting a WebGrid with a click?

Running into an issue with my webgrid and search button. It works perfectly if I search first, updating the grid with results. But when I click on a header to sort the grid, the search button stops working. Can't seem to figure out how to solve this d ...

Adjusting the styling of a webpage in real-time

Here is the CSS code I am working with: .myTabs .JustForFun .ajax__tab_inner:hover { width: 109px; background: url ("/images/csc_tr.png") no-repeat 100% 0%; margin-right: 2px; background-color: #BBC614; } I want to change the background-c ...

What could be causing my React button to stop functioning as a link to an external website when using anchor tags?

I recently created some buttons for my website using React. Initially, everything was working perfectly with the buttons, but suddenly they stopped functioning. Strangely, I didn't make any alterations to the code and I'm puzzled as to why they a ...

The AudioContext feature is functioning properly on Google Chrome but experiencing issues on Safari

In Safari, I understand that audio context needs to be created after user interaction. Despite this knowledge, the code below still didn't produce the desired result. HTML <button onclick="play">Play</button> Javascript functio ...

What is the process of transferring a variable from the view to the $scope using the $window service?

How can I properly initialize data using ng-init and retrieve it in a controller? Within my view form, I have an input field like this: <input class="form-control" type="text" id="name" name="name" ng-model="type.name" required="tr ...

Interact with HTML style attribute using JavaScript

Is there a way to retrieve a specific CSS property from the style attribute of an HTML element, without considering the stylesheet or computed properties? For example: <div style="float:right"></div> function fetchStyleValue(element, propert ...

Fixing the "Unknown error status: Error: The uid provided must be a non-empty string containing no more than 128 characters" issue in Firebase Functions is crucial for seamless performance

In my firebase application, I am attempting to create a new user by transferring data from the UI to a callable function. The process involves: Creating a user account using an email and password. Adding a display name followed by creating a profile in a ...