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

What is the process behind executing the scripts in the jQuery GitHub repository when running "npm run build"?

Check out the jQuery repository on GitHub. Within the jQuery repo, there is a "build" folder. The readme.md mentions the npm command: npm run build This command triggers the execution of scripts in the build folder to complete the building process from ...

What is the best way to execute an API function call within an ng-repeat loop?

I'm encountering an issue with a scope function in my controller that calls an API to retrieve data from a database. This scope function is being used within an ng-repeat loop. However, when I try running the application, it becomes unresponsive. Whil ...

Exploring ways to access elements within shadow-root (open) in Angular using SVG.js

I'm currently tackling a project involving Angular Elements. Within this specialized component, my goal is to incorporate SVG.js 3+. However, due to the necessity of utilizing ViewEncapsulation.ShadowDom in my component, I am encountering challenges w ...

Successfully passing props to the image source using React/Next.js

Currently, in my implementation with React and Next.js, I am utilizing next-images for importing images. I am looking for a solution to pass data directly to the img src attribute, like so: <img src={require(`../src/image/${data}`)} /> It appears t ...

Navigating the Seas of Angular Frontend

After extensive research, I have been unable to find the precise answer I am seeking. Upon beginning my journey with Sails app development (a new venture for me), it came to my attention that the framework creates its own frontend using EJS by default. T ...

Equal size images displayed within cards in Material UI

Is there a way to create a list of Material UI components with images that have uniform height, even if the original images vary in size? I want to make all image heights responsive and consistent across all cards. Any suggestions on how to achieve this? ...

Using identical content in various template slots

Is it possible in vuejs to assign the same content to multiple slots without repeating it? For example: <base-layout> <template slot="option"> <span :class="'flag-icon-' props.option.toLowerCase()" />{{ countriesByCode ...

Utilizing AMAZON_COGNITO_USER_POOLS in conjunction with apollo-client: A comprehensive guide

Struggling to populate my jwtToken with the latest @aws-amplify packages, facing some challenges. Encountering an error when attempting to run a Query: Uncaught (in promise) No current user It seems that when using auth type AMAZON_COGNITO_USER_POOLS, I ...

The declaration file for module 'react/jsx-runtime' could not be located

While using material-ui in a react project with a typescript template, everything is functioning well. However, I have encountered an issue where multiple lines of code are showing red lines as the code renders. The error message being displayed is: Coul ...

Only display the element if there is corresponding data available

I have implemented the angular ng-hide directive to conceal certain markup when there is no data present: <li class="header" ng-hide = " todayRecents.length === 0 ">today</li> At this point, ng-hide simply applies a display value of 'non ...

Generating a linked pledge with AngularJS

I need to create a linked commitment for my service provider: this.$get = function($q, $window, $rootScope) { var $facebook=$q.defer(); $rootScope.$on("fb.load", function(e, FB) { $facebook.resolve(FB); }); $facebook.api = functi ...

When I click on .toggle-menu, I want the data-target to have a toggled class and the other divs to expand

Looking to achieve a functionality where clicking on .toggle-menu will toggle a class on the specified data-target element and expand other divs accordingly. jQuery(document).ready(function() { var windowWidth = jQuery(window).width(); if (win ...

Can Regex expressions be utilized within the nodeJS aws sdk?

Running this AWS CLI command allows me to retrieve the correct images created within the past 45 days. aws ec2 describe-images --region us-east-1 --owners self -- query'Images[CreationDate<`2021-12-18`] | sort_by(@, &CreationDate)[].Name&apos ...

Is it really impossible to post complex JSON parameters with Restangular?

Is it possible to send a complex JSON object to a PUT route using Restangular? Restangular.one('model3ds', model.uuid).put( api_key: "blabla" model3d: { is_public: true } ) However, the data sent by Restangular appears as: ...

Tips for extracting the data from a resolved promise

As a beginner in Angular, I am facing some difficulties in figuring out how to extract the value from a resolved promise. In my code, I have used $q.all([element1.$promise, e2.$promise]). This returns element1 as a JSON object. However, for element2 which ...

In Visual Studio Code, beautification feature splits HTML attributes onto separate lines, improving readability and code organization. Unfortunately, the print width setting does not apply

I have done extensive research and tried numerous solutions, When using Angular and formatting HTML with Prettier, it appears quite messy as it wraps each attribute to a new line, for example: <button pButton class="btn" ...

Trying to call an applet method using JavaScript will not be successful

When trying to invoke methods of a Java applet using JavaScript, I encounter an issue that requires the site to be added to trusted sites and security set to low in order for it to work properly. Otherwise, an error is thrown: Microsoft JScript runtime ...

"Filtering a JSON File Based on Button Data Attributes: A Step-by-

I am working with a set of buttons that have specific data-map attributes as shown below: <button class="btn btn-default mapper" data-map="2015-11-13">Monday</button> <button class="btn btn-default mapper" data-map="2015-11-14">Tuesday&l ...

Can JavaScript bypass the need for an html page and go directly to the printing process?

Is it possible for a user to click a "print" button and have the printer start printing? Please note that there is already a server process in place (via AJAX) that can respond with success for printing or return HTML content for display, so that is not a ...

troubleshooting Axios errors in React applications

User/Project.js: import React, { useState, useEffect } from "react"; import Axios from "axios"; const Project = () => { const [projectName, setprojectName] = useState(""); const [projectDescription, setprojectDescriptio ...