Invoke an AngularJS directive in real-time

I am currently developing an Angular 1 application where I need to invoke different directives based on a specific value within an ng-repeat loop. As of now, I am using ng-if to render the directive that matches the condition. However, my concern is that as the number of directives grows to potentially 100 in the future, having to use multiple ng-if statements for each one may not be the most efficient approach.

Below is a snippet of my code:

Template calling the directive

<render-directive ng-if="data.length !== 0" data="data"></render-directive>

Template of renderDirective

<div ng-repeat="element in data">
  <div ng-if="element.item === 'motor'">
    <render-motor motor-id="element.id" name="element.item"
              checked="element.params.switch"></render-motor>
  </div>

  <div ng-if="element.item === 'adc'">
    <render-adc adc-id="element.id" name="element.item"></render-adc>
  </div>
</div>

While only two directives are shown here for simplicity, in reality, I am already utilizing more than 10 directives with the potential for this number to reach 100.

Is there a more efficient way to handle this situation without using ng-if for every single directive?

Please let me know if any part of my question requires further clarification.

UPDATE

To clarify my requirements, I have an array containing items with a 'item' property, and I want to dynamically call a directive based on this property. For example,

  • for item = "motor", I need to utilize the motorDirective
  • for item = "switch", I should employ the switchDirective
  • for item = "led", I ought to make use of the ledDirective

and so forth.

Answer №1

I encountered a challenge that required me to modify my response in order to successfully pass a scope to ng-bind-html.

Furthermore, using a polymorphic directive offers a more elegant solution, preserving the declarative aspect of a table-driven approach as well.

The key component of the ultimate solution lies within the polymorph directive:

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

app.controller('elementsCtrl',['$scope', function($scope){
  
  $scope.elements = [
    {type: 'motor'},
    {type: 'adb'},
    {type: 'led'},
    {type: 'motor'}
  ];
}]);

app.directive('polymorph', ['$compile', function($compile){
  return{
    restrict: 'E',
    scope: {
      type: '@',
      item: '='
    },
    link: function(scope, element, attr){
      var result = $compile('<div '+ scope.item.type +'></div>')(scope);
      element.append(result);
    }
  }
}]);

app.directive('motor', function(){
  return{
    restrict: 'A',
    replace: true,
    template: '<div style="color:blue;">{{item.type}}</div>'
  }
});


app.directive('led', function(){
  return{
    restrict: 'A',
    replace: true,
    template: '<span style="color:green;">{{item.type}}</span>'
  }
});

app.directive('adb', function(){
  return{
    restrict: 'A',
    replace: true,
    template: '<p style="color:red;">{{item.type}}</p>'
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>


<div ng-app="app" ng-controller="elementsCtrl">
  <div ng-repeat="element in elements">
    <polymorph type="{{element.type}}" item="element"></polymorph>
  </div>
</div>

Answer №2

Make sure to utilize $compile within the renderDirective function.

During the compilation phase, it is essential to compile the dynamically requested directive.

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

The .change() function is only executing once and not triggered by multiple clicks

I have a JavaScript file that runs automatically through an HTML script. The issue I am facing is with the putToggleCall() function, which should be triggered every time one of the toggles is clicked. However, it only executes once, even before the docum ...

Positioning Images at the Top of the Screen in React Native

I have two images that I would like to display side by side at the top of the screen. <View style={styles.container}> <View style={styles.topWrapper}> <Image source={TOP_START_GRAPHIC} style={styles.topStartImage} /> ...

`The Issue with Ineffective Slider Removal`

Below is the complete code: import React, { Component } from "react"; import "./App.css"; import Slider from "@material-ui/core/Slider"; import Typography from "@material-ui/core/Typography"; class App extends Compo ...

Setting response query correctly in Solr using AJAX

Inspired by an example of using Solr's JSON output for AJAX, I have incorporated a drop-down menu into my project form and introduced faceting to the parameters. Parameters: function getstandardargs() { var params = [ 'wt=json' ...

Is it possible to resolve the error message "Uncaught TypeError: Cannot read property 'node' of undefined" when utilizing d3-tip with npm?

After installing d3": "^3.5.17" and "d3-tip": "^0.7.1" via npm (d3-tip documentation), the following code was added to my index.js file: var d3 = require('d3'); var d3tip = require('d3-tip')(d3); console.log('d3 version', d3. ...

Transform a string (variable) into an object using JSON.parse, encountering an unexpected token error

I am struggling with parsing a string variable back to an object. Despite searching through various posts on this issue, I have not found a solution that works for me. if(subMatch.match(/\{.*\}/)){ /// new Object of some sort var o ...

Dealing with errors in multer and express-validator aspects

Is there a way to validate a form that includes an image using multer and other fields with express-validator? I keep encountering an undefined error (req.validationError) in the post route. Any suggestions on how to resolve this issue? server.js const e ...

Fixing the 'window is not defined' Error in Node JS through Command Line

Trying to incorporate Angular JS using 'require' in my code snippet: var ang = require('angular'); However, encountering an error: ReferenceError: window is not defined I am aware that the window object is not defined in the Node co ...

What is the best way to implement momentJS globally in VueJS 2?

Currently working with Vue.js version 2.6.11 Trying to set up in main.js as follows: import moment from 'moment' moment.locale('nl'); Object.definePrototype(Vue.prototype, '$moment', { value: moment }); Encountering an error ...

What is the significance of utilizing response.json() for accessing JSON objects on both the server and client sides?

Just starting out with the MEAN stack, I've included my API code below where I'm using res.json(random) to send a random password. module.exports.changePass = function (req, res) { console.log(req.body.email) db.user.find({ where: { name: ...

How can I merge an array of objects in lodash?

I am facing a challenge with merging an array of objects in JavaScript. My goal is to combine them into a single object using either a JS library or lodash. Here is how my array looks: [{ 2017: { a: "100", b: "200" ...

After reaching the character limit, errors occur due to data being sent through Ajax requests on keyup

My website has a feature where users can input zip codes and get information based on that. However, I am facing an issue with the ajax call when users continue typing beyond the required number of characters for zip code entry. Even though the additional ...

Display a message stating "No data available" using HighCharts Angular when the data series is empty

My Angular app utilizes Highchart for data visualization. One of the requirements is to display a message within the Highchart if the API returns an empty data set. I attempted a solution, but unfortunately, the message does not appear in the Highchart a ...

Iterate through a large JavaScript object using setTimeout

What is the most efficient way to iterate through large object elements without freezing the browser? I have successfully looped through arrays using setTimeout/setInterval in this manner: var i = 0; var l = arr.length; var interval = window.setInterval( ...

Exploring the Dynamic Duo: Laravel Echo and JQuery

After including Echo in Vue.js' resources/assets/js/bootstrap.js, one of my components is throwing an error The error message states: "Error in mounted hook: 'TypeError: $ is not a function'" When I remove the Echo import, everything run ...

XMLHttpRequest response: the connection has been terminated

After developing a Flickr search engine, I encountered an issue where the call to the public feed or FlickrApi varies depending on the selection made in a drop-down box. The JSONP function calls provide examples of the returned data: a) jsonFlickrApi({"ph ...

The POST method in Node JS request-promises does not properly handle string inputs

When I am trying to establish a connection between my node.js module and another server, I utilize the 'request-promise' library. My implementation for posting data looks like this: rp.({ method: 'POST', headers:{ 'Conte ...

What is the process for attaching a dynamically generated object to the document's readiness event?

One of my tasks involves dynamically generating a slider element using the code snippet below: function NewDiv(){ for (var count=0; count < parseFloat(sessvars.storey_count); count++) { var string="<br><div ...

Creating a callback using a factory method

This is the approach I have implemented in my angular controller : $scope.invokeJersey = function(display) { var selectedShows = []; var show; for (show in shows) { var temp = {}; temp.name = show; temp.properties = shows[show].selectedShow; selectedShow ...

Fetching a collection from Cloud Firestore using Angular and Firebase

I'm looking to figure out how to retrieve lists from cloud firestore. Here is how I upload a list : export interface Data { name: string; address: string; address2: string; pscode: string; ccode: string; name2: string; } constructor(pri ...