Angularjs directive change name format
I didn't quite figure out how to write AngularJS directives even after looking at many blogs. Basically I have an array of names in the "lastname, firstname" format. I want to write a directive to make it "firstname lastname"
My html is like this
<div ng-repeat="names in nameArray"
<custom-name-format> {{names}} </custom-name-format>
</div>
How do I pass the 'names' parameter to a directive?
controller:
angular.module('nameApp').directive('customNameFormat', function() {
// how do I access and manipulate {{names}} here?
});
+3
source to share
7 replies
Try using a filter instead of a directive .
Here's a JsFiddle link .
Code examples :
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;
};
});
Hope it helps.
+4
source to share
In 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>
+3
source to share
you can use jquery as well, but in Angular can be accessed with attributes too
<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);
}
}
});
+2
source to share
I think this will help you
var demo = angular.module('demo', []);
demo.directive('displayTime', function($parse) {
return {
restrict: 'E',
replace: true,
transclude: false,
template: '<ul><li ng-repeat="data in datas">{{data.first}}----- {{data.last}}</li></ul>',
link: function (scope, element, attrs, controller) {
scope.datas = [{first:"pavan",last:"techie"},{first:"sword",last:"fish"}];
}
}});
+2
source to share