Modify the name format using an AngularJS directive

I've been struggling to understand how to effectively write AngularJS directives, even after reading various blogs. The issue I am facing is with an array of names in the format "lastname, firstname". My goal is to create a directive that will display them as "firstname lastname."

Here is the structure of my HTML:

<div ng-repeat="names in nameArray"
    <custom-name-format> {{names}} </custom-name-format>
</div>

Could you please guide me on how to pass the 'names' parameter to the directive?

Controller:

angular.module('nameApp').directive('customNameFormat', function() {
    
    // How can I access and manipulate {{names}} within this directive?
});

Answer №1

Consider using filter in place of directive.

Take a look at the JsFiddle demo.

Example Codes:

HTML:

<div ng-app="myApp">
    <ul ng-controller="YourCtrl">
       <li ng-repeat="name in names">
           {{name.name | customNameFormat}}
        </li>
    </ul>
</div>

JS:

'use strict';

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

app.controller('YourCtrl', ['$scope', function ($scope) {

    $scope.names = [
        {name:'Doe, John'},
        {name:'Naperi, Alberto'},
        {name:'Last, First'},
        {name:'Espolon, Justin'},
        {name:'Bor, Em'},
        {name:'Pik, El'},
      ];

}]);

app.filter('customNameFormat', function() {    

    return function(input) {
        var nameStr = input.split(',').reverse().join(' ');
        return nameStr;
    };

});

Hopefully this solution works for you.

Answer №2

It seems like a directive is unnecessary in this case. A filter would be a better choice, and you can easily pass arguments to the filter.

Here's how it looks in HTML:

{{ dataToFilter | myCustomFilter : argument}}

And here's how you do it in JavaScript:

$filter('myCustomFilter')(dataArray, argument)

Answer №3

Within the directive

angular.module('nameApp').directive('customNameFormat', function() {
  return{
    scope:{
    names : '='
    },
    link: function(scope,elem,attr){
       var nameStr = scope.names //lastname, firstname
       var newNameStr = nameStr.split(',').reverse().join(' ');
       elem.html(newNameStr);

    } 

 }

})

<div ng-repeat="names in nameArray"
   <custom-name-format names="names" ></custom-name-format>
</div>

Answer №4

To assign a specific attribute to the name, use the following method:

<div ng-repeat="names in nameArray">
    <custom-name-format custname="{{names}}"> {{names}} </custom-name-format>
</div>

Then, you can retrieve the names assigned to custname in your directive using this syntax:

scope: {
  custname: '@'
}

Answer №5

Using Angular, you have the option to access attributes in a similar way to using jQuery.

<div ng-repeat="names in nameArray"
    <custom-name-format custom-attr="{{name}}"> {{names}} </custom-name-format>
</div>

controller:

angular.module('nameApp').directive('customNameFormat', function() {

     return {
        restrict: 'A',

        link: function (scope, el, attrs) {
alert(attrs.customAttr);
}
}
});

Answer №6

If you need to reorganize a name, consider utilizing regex matching.

const segments = fullName.match(/(\w+), (\w+)/)
segments[2] + " " + segments[1]

Answer №7

I believe this solution will be beneficial for you

let app = angular.module('app', []);
app.directive('showTime', function($parse) {
    return {
        restrict: 'E',
        replace: true,
        transclude: false,
        template: '<ul><li ng-repeat="item in items">{{item.first}}----- {{item.last}}</li></ul>',
        link: function (scope, element, attrs, controller) {
          scope.items = [{first:"john",last:"doe"},{first:"apple",last:"pie"}]; 
        }
    }});

JS FIDDLE

Answer №8

Learn how to Update your Name using AngularJs

body{
  font-family: 'arial';
}
ul,li{
  list-style: none;
}
ul{
  padding: 0px;
  margin:0px;
}
.name-demo{
  border: 1px solid #333;
  padding: 10px;
}
.name-demo li{
  margin-bottom: 15px;
  margin-top: 15px;
}
.name-demo li input{
  border:1px solid #e4e4e4;
  height: 35px;
  padding: 5px;
  width: 200px;
  margin-left: 10px;
}
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<p>Learn how to Update your Name using AngularJs</p>

<div ng-app="myApp" ng-controller="myCtrl">
  <div class="name-demo">
    <ul>
      <li>
        First Name: <input type="text" ng-model="firstName">
      </li>
      <li>
        Last Name: <input type="text" ng-model="lastName">
      </li>
      <li>
        Your full name is: {{firstName + " " + lastName}}
      </li>
    </ul>
  </div>
</div>

<script>

var app = angular.module('myApp',[]);
app.controller('myCtrl', function($scope){
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>

</body>
</html>

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 issue of duplicated elements arises when Ajax is utilized within Django

Upon form submission, a Graph is generated using Plotly. Utilizing Ajax to submit the form without refreshing the page results in duplicating the form div on the screen. How can this issue be resolved? The code snippet below showcases my implementation wit ...

React Native: error - unhandled action to navigate with payload detected by the navigator

Having trouble navigating from the login screen to the profile screen after email and password authentication. All other functions are working fine - I can retrieve and store the token from the auth API. However, when trying to navigate to the next screen, ...

Refresh Form (Reactive Forms)

This is the HTML code snippet: <div class="container"> <ng-template [ngIf]="userIsAuthenticated"> <form [formGroup]='form' name="test"> <div class="form-group"> <input type="text" class="form-contr ...

Unlock the power of React Testing Library with the elusive waitFor function

I came across an interesting tutorial about testing React applications. The tutorial showcases a simple component designed to demonstrate testing asynchronous actions: import React from 'react' const TestAsync = () => { const [counter, setC ...

Error: Trying to access property '1' of an undefined value is not allowed

I'm experiencing a problem that I can't seem to solve. The issue arises after the user logs in. I am using useEffect() to retrieve the user data by using a secret token from localstorage. Everything seems to be working fine - the data, the secret ...

Choose between creating an observable pipe within a function or storing it in a variable

Currently, I have a functional code snippet that leverages the Angular service to create an Observable pipeline. This pipeline utilizes operators like mergeMap, filter, map, and shareReplay(1) to manage user authentication and fetch the onboarding status f ...

What mechanism does the useState() function utilize in React to fetch the appropriate state object and function for a functional component when employing the state hook?

Currently focusing on deepening my understanding of the useState hook in react. I have a question regarding how useState retrieves the state object and modifier function specific to each functional component when it is called. What I'm wondering is w ...

Emails can be sent through a form without the need for refreshing

I am currently working on a webpage that utilizes parallax scrolling, and the contact box is located in the last section. However, I encountered an issue where using a simple HTML + PHP contact box would cause the page to refresh back to the first section ...

Execute Jquery ajax only on the initial invocation

When I am using ajax post in jQuery to build a portion of a page, I am encountering an issue where it only runs once. Below is the code snippet I am working with: <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery ...

React HTML ignore line break variable is a feature that allows developers to

Can you help me with adding a line break between two variables that will be displayed properly in my HTML output? I'm trying to create an object with a single description attribute using two text variables, and I need them to be separated by a line b ...

Is there a way to display the back and forward buttons on a popup window opened through window.open or self.open in Chrome browser?

When I try to open a popup window using the code snippet below, I am facing some issues. self.open('myJSPPage','ServicePopUp','height=600,width=800,resizable=yes,scrollbars=yes,toolbar=yes,menubar=yes,location=yes'); Afte ...

Trouble arises when attempting to showcase document fields in MongoDB

As a beginner in programming, I am putting in my best effort to figure things out on my own. However, I seem to be stuck without any guidance. I am attempting to display all products from the mongoDB based on their brand. While I have successfully set up a ...

comparing values in an array with jquery

I am attempting to retrieve the phone number and mobile number from an array using jquery. jQuery: var data = $('#PhoneLabel').text(); var array = data.split(', '); $.grep(array, function (item, index) { if (item.charAt(0) === &ap ...

implementing a delay after hovering over a CSS hover effect before activating it

I'm trying to achieve a specific effect using JavaScript or jQuery, but I'm struggling to figure it out. I have created a simple CSS box with a hover effect that changes the color. What I want is for the hover effect to persist for a set amount o ...

Is your YQL JSON script failing to provide the expected output?

Here is a script that I have copied almost directly from this. Why is it that the code below does not seem to return anything? ajax.html: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html dir="lt ...

Enhance Website Speed by Storing PHP Array on Server?

Is there a way to optimize the page load time by storing a PHP array on the server instead of parsing it from a CSV file every time the page is reloaded? The CSV file only updates once an hour, so constantly processing 100k+ elements for each user seems un ...

render target in three.js EffectComposer

When we utilize an EffectComposer, the scene is rendered into either composer.renderTarget2 or composer.renderTarget1. In a particular example, I came across this: renderer.render( scene, camera, composer.renderTarget2, true ); renderer.shadowMapEnabled ...

Protractor - I am looking to optimize my IF ELSE statement for better dryness, if it is feasible

How can I optimize this code to follow the D.R.Y principle? If the id invite-user tag is visible in the user's profile, the user can request to play a game by clicking on it. Otherwise, a new random user will be selected until the id invite-user is di ...

Adding HTML to a webpage through the use of JavaScript's .innerHTML functionality

Currently in the process of creating a website template, I have made the decision to experiment with using an external JS file for inserting HTML at the top of the page to streamline navigation (eliminating the need for manual copying and pasting). My att ...

What is the best method for swapping out an iframe with a div using Javascript?

Having an issue with loading an external HTML page into an iFrame on my website. Currently facing two main problems: The height of the iFrame is fixed, but I need it to adjust based on the content's height. The content inside the iFrame does not inh ...