Directive that can be reused with a dynamic item name in ng-repeat

I've developed a reusable directive similar to a dropdown, but this dropdown opens in a modal and is functioning well.

The structure of my directive is as follows:

<p-select items="deptStations" header-text="Select " text="Select departure..." text-icon="ion-chatbubble-working" text-field="City_Name_EN" text-field2="City_Code" value-field="City_Code" ng-model="deptStation.value">
</p-select>
<p-select items="arrStations" header-text="Select " text="Select arrival..." text-icon="ion-chatbubble-working" text-field="D.City_Name_EN" text-field2="D.City_Code" value-field="D.City_Code" ng-model="arrStation.value">
</p-select>

This is the HTML structure of my directive:

<ion-content>
      <div class="list">
        <label ng-repeat="item in items | filter:search" class="item item-text-wrap" ng-click='validateSingle(item)'>
          {{item[textField]}} {{textField2 !== '' ? " (" + item[textField2] + ")" : ""}}
        </label>
      </div>
</ion-content>

However, I'm facing an issue when dealing with JSON data that has nested levels. For example:

[{City_Name_EN:'Abu Dhabi', City_Code:'AUH' },
 {City_Name_EN:'Alexandria',City_Code:'HBE' }]

In cases where there are 2 levels of nested JSON, like below, it does not work properly:

[{D:{City_Code:'AMM',City_Name_EN:'Amman'},
 D:{City_Code:'BKK',City_Name_EN:'Bangkok'}}]

So, I am looking for a way to dynamically handle this part: {{item[textField]}}

You can view my plunkr here: http://plnkr.co/edit/GxM78QRwSjTrsX1SCxF7?p=preview

Answer №1

When dealing with dynamic expressions like yours, it's best to have directives focus on a specific contract provided as the view model. If the consumer of the directive has different data formatting, it should be the responsibility of that component to provide the required contract for the directive. This way, you can maintain cleanliness in your code - that's my opinion.

To address your issue, you'll need to use a workaround to evaluate a multi-level property against an object. You can utilize $scope.$eval to assess any dynamic expression against the scope object. For example, evaluating a dynamic property like prop1.prop2.prop3 on a scope property item can be done using

$scope.$eval("prop1.prop2.prop3", item)
or
$scope.$eval("item." + "prop1.prop2.prop3")

In your directive:

Add a scope function to retrieve the item text and value:

$scope.getItemName = function(field, item){
   //here "this" represents the current child scope of ng-repeat
   return $scope.$eval(field, item);
   //return this.$eval("item." + field); 
}

and

 $scope.validateSingle = function(item) {
      $scope.text = $scope.$eval($scope.textField, item) + ($scope.textField2 !== '' ? " (" + $scope.$eval($scope.textField2, item) + ")" : "");
      $scope.value = $scope.$eval($scope.valueField, item);

     ...

Update your template to display the respective text:

    <label ng-repeat="item in items | filter:search" class="item item-text-wrap" ng-click='validateSingle(item)'>
      {{getItemName(textField, item)}} {{textField2 !== '' ? " (" + getItemName(textField2, item) + ")" : ""}}
    </label>

Plnkr

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

Uncovering the hidden treasures of checkbox values using jQuery

I've encountered an issue with a form containing checkboxes. Some values are meant to be true by default, so I've hidden them using the following method: <input type=checkbox name="<%= _key %>" checked="checked" style="display:none" /& ...

Send both file and model data using AngularJS with FormData

When uploading an image using the file input type along with other user data, my model includes the User class: public class User { public int Id { get; set; } public string Name { get; set; } public int Rollno { get; set; } public byte[] ...

Troubles arise with loading Ajax due to spaces within the URL

I currently have two python files named gui.py and index.py. The file python.py contains a table with records from a MYSQL database. In gui.py, there is a reference to python.py along with a textfield and button for sending messages. Additionally, the g ...

Achieving Efficiency with Handlebars: Streamlining Remote Template Organization and

I am looking for a way to better organize my HB template by splitting it into different HTML files. In this case, I have created a file called helpers.html. This file contains two script tags: <script id='alert' type='text/template>... ...

Exploring the Power of v-for in Nested Objects with Vue

I currently have a dataset in the following structure: itemlist : { "dates": [ "2019-03-15", "2019-04-01", "2019-05-15" ], "id": [ "arn21", "3sa4a", "wqa99" ], "price": [ 22, 10, 31 ] } My goal is t ...

Utilizing Angular 6 and JavaScript to invoke two functions within an (ngClick) event in both the Component and JavaScript

I have a requirement to execute two functions in my click event, one for my component and the other for a custom JavaScript function. Here is the code snippet: Angular click event: <button type="button" class="btn btn-primary" (click)="Plans(); " [att ...

Decoding JavaScript content with Python

Currently, I am dissecting this specific portion of HTML <script type="text/javascript"> var spConfig = new Product.Config({"attributes":{"150":{"id":"150","code":"size_shoe","label":"Schuhgr\u00f6\u00dfe","options":[{"id":"494","label ...

Creating a specialized pathway with variable inputs within the URL

As a Node beginner, I am facing a challenge with an Express exercise on dynamic routes. The task at hand is to create a route that can accept dynamic arguments in the URL path and respond with a quote from the respective author. Here's a snippet of th ...

When directed to a different page, Fetch does not activate

Having trouble getting the fetch function to run more than once in my application. It works the first time, loading the page with received data, but when I navigate to a new URL without refreshing the page, nothing changes - not even the state. The same is ...

What is the method for altering the look of a button using JavaScript?

As a beginner in web development, I have a question. Typically, I know how to style the submit button when it's created in the HTML page using CSS. However, I'm wondering if it's possible to apply CSS styling to the JavaScript block instead. ...

When opening a dialog at the bottom of the page, the window will automatically scroll to the top

I'm encountering an issue with a page that has a width exceeding 100% (2000px). Whenever I click to display a dialog from a button located at the end of the horizontal page, the window automatically scrolls back to the beginning of the page before sho ...

When working with AngularJS, you can enhance your application by implementing a global AJAX error handler if one has

Is there a way to set a global AJAX handler that will only be called if an error handler is not already defined for a specific AJAX call? Some of my AJAX calls need to execute certain logic if an error occurs (such as re-enabling a button), while others s ...

React component experiencing double execution of SetTimeout function

Every time I render the App component, the code inside setTimeout seems to be running twice. I've noticed that setTimeout executes after the call stack is cleared. I wonder if this has any connection to the issue. Could it be related to how React ha ...

Issue encountered while retrieving ImageURI using Phonegap

Currently, I am working on a feature that allows users to choose a photo from their camera or gallery using PhoneGap 3.0.0 with Angular integration. However, I have encountered an issue where it only seems to work for photos taken with the camera. Below ...

Display Angular errors specifically when the input field is filled out and contains invalid data

I need help with toggling an error area on my form so that it only appears once there is input. It seems unnecessary for errors to show up if the user hasn't even started typing. <form name="registerForm"> <input type="email" name="email" ...

Nested ng-repeat containing single select checkboxes

For more information, please refer to the demo plunkers provided below: Demo Plunker Example1 The code snippet for Example1 is as follows: <tr ng-repeat="class in Classes"> <td>{{class.name}}</td> <td&g ...

I encountered a permission denied error when trying to enter DEBUG=app ./bin/www in Node.js

After renaming 'my-application' to just 'app', I encountered an issue when running the DEBUG command in the terminal: I used DEBUG=app ./bin/www Originally, it was named 'my-application' as created by express. However, after ...

Mastering the Art of Displaying Links in Columns within a Table Using ReactJS

I have the following code that fetches data from the backend and displays it in a table. Everything is working correctly. Now, I need to make the first column in the table appear as a link. How can I achieve that? const EditController = () => { c ...

Mapping geographic coordinates with a null projection using D3

With d3.geo.path having a null projection due to TopoJSON already being projected, it can be displayed without any additional transformation. My goal is to plot data in the format of [longitude, latitude] on a map. Here is a simplified version of my code: ...

What is the best way to create and implement custom declaration files that are not available on @types or DefinitelyTyped?

I have encountered a situation where I am using an npm package named foo that is not available on DefinitelyTyped or may be outdated. Despite this, I still want to consume it under stricter settings like noImplicitAny, so I need to create custom definition ...