Directive Template with Dynamic Fields (AngularJS)

I am interested in creating a custom directive that can bind to any object, allowing me to specify the field used in the template for display. Previously, I was limited to using {{item.Name}}, but now I want the flexibility to define the display field.

Current Implementation:

var myDirective = function () {
    return {
        restrict: 'E',
        scope: {
            items: '='
        },
        template:
        "<div class='holder'>"
          + "<a data-ng-repeat='item in items' data-ng-click='myClick(item)'><i class='fa fa-times'/>{{item.Name}}</a>"
          + "</div>",
        
        controller: function ($scope) {......}
      }
}

Desired Approach:

var myDirective = function () {
    return {
        restrict: 'E',
        scope: {
            items: '=',
            display_field: 'Name',
            icon_field: 'fa fa-times'
        },
        template:
        "<div class='holder'>"
          + "<a data-ng-repeat='item in items' data-ng-click='myClick(item)'><i data-ng-class='{{item.icon_field}}'/>{{item.display_field}}</a>"
          + "</div>",
        
        controller: function ($scope) {......}
      }
}

Usage Example:

<my-directive items="myItems" display_field="OtherProperty" icon-field="iconProperty" />

Fiddle Demo: http://jsfiddle.net/1L7tdd1p/

Answer №1

Approaching the correct solution. Remember that angular expressions are a subset of Javascript expressions. When accessing a property with a dynamic name, use bracket notation:

{{ item[display_field] }}

An object's key can be any value, not limited to strings. Bracket notation allows you to access an object's property using any expression as a key:

var obj = {};
obj[1] = 'a';
obj.asdf = 'b';
obj[{}] = 'c';
console.log(obj[1], obj['asdf'], obj[{}]);

Furthermore, it seems there might be confusion about the scope option. It is intended for specifying bindings that your directive will inherit from the element it is applied to, defining the type of these bindings. Default values cannot be set using this option. Refer to Use of symbols '@', '&', '=', and '>' in custom directive's scope binding: AngularJS.

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

//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

function MyCtrl($scope) {
  $scope.name = 'Superhero';
}

myApp.directive('foo', function() {
  return {
    restrict: 'E',
    scope: {
      items: '=',
      prop: '@' // this declared a
    },
    template: " <a data-ng-repeat='item in items'><br/>{{item[prop]}}</a>",
    
    controller: function($scope) {}
  }

});

myApp.controller("appController", function($scope) {
  $scope.Items = [{
    "id": 1,
    "name": "aaaa"
  }, {
    "id": 2,
    "name": "bbbb"
  }]
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.min.js"></script>
<div ng-app='myApp' ng-controller="appController">
  <foo items="Items" prop='name'></foo>
</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

assigning attributes to web addresses

Is there a way to set a style property for webpages by targeting addresses that contain /index.php/projecten/ instead of specifying each complete address in the code? Currently, I am using the following code: <ul class="subnavlist" style="display: &l ...

Problem with Bootstrap loading state when certain input fields are required

Just starting out with Bootstrap 3 and looking to integrate the loading state button function into my form. I've set up an input field with the required option as shown below. <form> <input class="input" name="title" type="text" required / ...

Tips for incorporating conditions when updating data in MongoDB

I am looking for assistance with updating the secondary phone number in the code below. I want to update it only if a 10-digit number is passed from the web form; otherwise, I would like to use the already inserted phone number during the insert operation. ...

Confirming whether the digit entered in jQuery is a number

My website has a user input field where numbers are expected to be entered. I wanted to find a convenient way to validate the input using jQuery. After some research, I discovered jQuery's built-in function called isDigit. This handy function allows ...

HapiJS commences an extended duration background process

Is there a way to achieve the functionality of a PHP exec function in HapiJS? I have a scenario where the user submits a processing job that requires running in the background for a significant amount of time. An essential requirement is to provide the us ...

Having trouble with TypeScript Library/SDK after installing my custom package, as the types are not being recognized

I have created my own typescript library using the typescript-starter tool found at . Here is how I structured the types folder: https://i.stack.imgur.com/igAuj.png After installing this package, I attempted a function or service call as depicted in the ...

My Node.js script seems to be experiencing some issues

Could you provide me with a helpful tip? Here is the code I am working on: const request = require('request'); const cheerio = require('cheerio'); function getUrls(url) { const baseUrl = 'https://unsplash.com'; let u ...

Switching on the click functionality

I was able to successfully toggle a boolean variable along with some other options. However, I encountered an issue when trying to create another click function for a different button to set the boolean variable to false. Here is my code: let manageme ...

Interact with Dialogflow using fulfillment to retrieve responses by opening an HTTP URL

Despite my efforts, I have yet to find a satisfactory solution. I am in the process of creating an agent on Dialogflow. This agent will be embedded on a webpage, not as part of Facebook Messenger or Google Assistant. The purpose of this agent is to guide ...

Combining an if-statement with an HTML button within a single function in JavaScript

I'm currently developing an HTML table that includes fields that must be filled, but I want to allow one of the fields to be optional. The structure of my code is as follows: name.html ... <table> <tr> <td>Number 1:</td& ...

Display a component just once in React or React Native by utilizing local storage

I am struggling with a situation where I need to display a screen component only once using local storage. It's really frustrating. App.js ... constructor(props) { super(props); this.state = { isLoading: false, }; } component ...

Is it possible for me to use AJAX to load content from a string? I am attempting to postpone the activation of certain HTML

I need help optimizing my HTML page that includes certain sections with large Javascript files and images, which are initially hidden. Even when set to "display: none," the browser still loads all the content. One solution could be moving those sections in ...

Designing a Dynamic Floating Element that Shifts with Scroll Movement

Hey there everyone!, I am currently working on a project in Wordpress and I was wondering if anyone has experience creating a floating widget that moves along with the page as you scroll. Any suggestions on how to achieve this? Would it involve using Javas ...

Node-express can seamlessly switch between multiple databases dynamically

After extensive searching for a solution to my problem, I have come up empty-handed. If anyone has experience in similar situations, your help would be greatly appreciated. I have developed an application server in Node Express with MySQL as the database. ...

What is the best way to determine the remaining time until a cookie expires in seconds?

I recently set a cookie with an expiration time of 2 minutes. Now, I am looking for a way to display a countdown in HTML showing the seconds remaining before that specific cookie expires using Angular 2. ...

Unable to execute $http in AngularJS Plunker

Having trouble running $http on the Plunker. Can you please review my code and assist me? var QuizApp = angular.module('QuizApp', []); QuizApp.controller('QuizController', ['$scope','$http',function($scope,$http) { ...

Tips for saving the recently assigned IP address from Terraform?

My current project involves cloud provisioning with Terraform on an EC2 instance, where the process is automated to begin when a request is sent from the front end to the back end. In the backend, I am using Node.js and implementing shell scripts to execu ...

The `tailwind.min.css` file takes precedence over `tailwind.css` in my Nuxt

Having trouble configuring Tailwind to use a custom font without it overriding the tailwind.css file and not displaying the changes? https://i.stack.imgur.com/ExDCL.png Check out my files below. // tailwind.config.js const defaultTheme = require('ta ...

If the option is not chosen, remove the requirement for it

I am in the process of creating a form that offers 3 different payment options: 1 - Direct Deposit 2 - Credit Card 3 - Cash at Office The issue I am facing is with the validation of input fields for Credit Cards. I want to make it so that these field ...

What could be causing the error "Cannot read the state property of undefined" to occur in my code?

I am facing an issue with my constructor that suddenly stopped working and I can't seem to figure out why. Upon analyzing the data, it appears that at line 24, everything is being read correctly including props. However, just one line later when tryi ...