Tips on using object fields as directive arguments in AngularJS

Is there a way for me to pass an object array to a directive and have it output specific fields that I specify at the location where I use the directive?

Let's look at an example:

//directive
app.directive('MyDirective', function() {
  return {
    restrict: 'A',
    templateUrl: 'my-directive.html',
    scope: {
      items: '@',
      field: '@'
    }
  };
});

// my-directive.html template
<div ng-repeat="item in items">{{ item.field }}</div>

The concept is to be able to use it with any object like this:

// object arrays
var phones = [{id:1,number:'555-5555'}, {id:2,number:'555-6666'}];
var persons = [{id:1,name:'John'}, {id:2,name:'Jane'}];


// directive usage
<div my-directive items="phones" data-field="???number???"></div>
<div my-directive items="persons" data-field="???name???"></div>

The desired outcome is to display the phone numbers and names. Is this achievable in Javascript?

Answer №1

To associate the items, simply connect them with '=':

.directive('myDirective', function() {
  return {
    restrict: 'A',
    template: '<div ng-repeat="item in items">{{ item[field] }}</div>',
    scope: {
      items: '=',
      field: '@'
    }
  };
})

Then implement it in this manner:

<div my-directive items="phones" field="number"></div>

Check out this demo.

Answer №2

Achieving this is absolutely doable, you just need to follow these steps:

Custom Directive Implementation:

myApp.directive('myDirective', function() {
    return {
        restrict: 'A',
        template: '<div ng-repeat="item in items">{{ getItemField(item) }}</div>',
        scope: {
          items: '=',
          field: '@'
        },
        link: function(scope, element, attr) {
            scope.getItemField = function (item) {
                return item[scope.field];
            };
        }

      };

Usage in HTML:

<div my-directive items="phones" data-field="number"></div>
<div my-directive items="persons" data-field="name"></div>

Fiddle Link

Answer №3

The solution does not require a directive, the one you may be seeking is ng-repeat:

var devices = [{id:1,name:'iPhone'}, {id:2,name:'Samsung'}];
var users = [{id:1,username:'user1'}, {id:2,username:'user2'}];

<li ng-repeat="device in devices">{{device.name}}</li>

<li ng-repeat="user in users">{{user.username}}</li>

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

Tips for creating a login page with AngularJS

For my dynamic web application, I am utilizing AngularJS to create a master page structure. In the index.html file, I have an ng-view where I can inject other pages while keeping the menu, header, and footer constant. index.html <body ng-app="mainApp" ...

Exploring Jasmine and Karma for testing Angular 5 HTTP requests and responses

I am brand new to the concept of Test-Driven Development (TDD) and I am currently in the process of debugging a complex Angular 5 application for the company I work for. The application is functioning without any issues, but now I need to incorporate test ...

Double dragenter events triggered before dragleave in HTML5 drag and drop functionality

Currently, I'm researching HTML5 Drag and Drop functionality by using this resource. However, I've encountered an issue with the dragenter event that seems to fire twice for child elements before the dragleave event. Because of this, the dashed b ...

Modifying the menu with Angular 4 using the loggedInMethod

Struggling to find a solution to this issue, I've spent hours searching online without success. The challenge at hand involves updating the menu item in my navigation bar template to display either "login" or "logout" based on the user's current ...

How can you ensure a code snippet in JavaScript runs only a single time?

I have a scenario where I need to dynamically save my .env content from the AWS secrets manager, but I only want to do this once when the server starts. What would be the best approach for this situation? My project is utilizing TypeScript: getSecrets(&qu ...

When trying to reference "this" and store it in a variable, it appears as undefined. However, DevTools show that it is actually defined

I've encountered an unusual situation in my React app involving the binding of "this" - I have a function within a component named "App" that is located in a separate file. In the main file, I've bound the "this" command to it. What's puzzl ...

Having difficulty transferring navigation props between screens using react-navigation

Within my ContactList component, I have utilized a map to render various items. Each item includes a thumbnail and the desired functionality is that upon clicking on the thumbnail, the user should be directed to a new screen referred to as UserDetailsScree ...

Running npm commands from the root directory while the package.json file is located elsewhere

Although I understand that it's not ideal, I am faced with a specific directory structure that cannot be changed: [projectRootDir] [src] [tests] [otherDirs] [configuration] package.json mocha.opts other files.. ...

Determine the variance between the final two items in an array composed of objects

I am trying to figure out how to calculate the difference in total income between the last two months based on their IDs. It seems that {income[1]?.total} always gives me a constant value of 900. Any suggestions on how I can accurately calculate the tota ...

Encountering an issue with React npm causing errors that I am unable to resolve

Hey there, I'm a newbie to React. After setting everything up, I encountered an error after running "npm start." Can anyone help me figure out how to fix this? Thanks in advance! Click here for image description ...

Next.js Configuration Files Explained

Currently, my application is functioning well with the use of Next.js and Next.js API tool for handling requests. The backend is managed through sanity.io which is working smoothly. In my sanity configuration setup, I have a dedicated file named 'san ...

Send a triggering function to two separate components

My objective is as follows: render() { return ( <div> <Child onTrigger={xxx} /> <button onClick={xxx} /> </div> ) } Upon clicking the button, I wish for some action to take place in ...

leveraging the situation and a clever opening

Currently, I'm diving into mastering the proper utilization of context and hooks. Initially, everything worked flawlessly while all components remained within a single class. However, troubles arose when I segregated them into multiple classes leading ...

Passing parameters between various components in a React application

Is it possible to pass a parameter or variable to a different component in React with react-router 3.0.0? For example, if a button is clicked and its onClick function redirects to another component where the variable should be instantly loaded to display a ...

Step-by-step guide to creating a transition effect when the input changes

I'm looking to add a unique effect to my dropdown menu My goal is to create an effect in which the placeholder moves up and the new value seamlessly takes its place, using JS, jQuery, CSS, and HTML. View before transition View after transition ...

Create your masterpiece on a rotated canvas

My goal is to draw on a canvas using the mouse, even after rotating and scaling the canvas container. The issue I am facing is that the mouse coordinates get affected by the rotation and scaling, making it difficult to draw correctly. I have tried switch ...

Using the JavaScript JSX syntax, apply the map function to the result of a

My aim is to create a structure resembling the following: <td> {phones.map((phone, j) => <p>{this.renderPhone(phone)}</p> )} </td> However, there may be instances where the phones array is not defined. Is it feas ...

Angular's onreadystatechange event is triggered when the state

Hey there, I'm new to Angular and had a question. Is it possible to use the $http service in Angular to trigger a function whenever there is any change in the ready state/status, not just for success or failure? If so, what would be the equivalent ang ...

The wordpress jquery dependency is failing to respond

After converting an HTML ecommerce template into WooCommerce, I am experiencing issues with the functionality. The Nivo slider and some other product features are not working properly. It seems like they are having trouble finding WordPress jQuery, even th ...

Issue with the intersection of mouse and camera rays in three.js

I've been working on a simple program that involves creating a clickable 3D object in Three.js. I've referenced my code from When I click directly on the object, it works as expected, but upon examining the resulting array, I noticed that the ob ...