Substr in angularJS to fetch the initials of the full name - angularjs

My question is related to creating substr in Angular.JS
Suppose i have a model:
$scope.myName = 'John Smith'
but when during the rendering of the model on the page i need only the initials of the name like:
<p>{{myName | some directive/filter }}<p>
Output should be :: JS
i tried creating many directives but unable to fetch the exact output even i have tried the limitTo filter but it give only the starting first 2 letters of the name.
Workbook is here

With assumption that name tokens are separated by SPACE , as given in your question
<body>
<div ng-app="myApp" ng-controller="namesCtrl">
<label>Name : {{name}}</label><br/>
<label>Short Name : {{name|shortName}}</label>
</div>
<script>
var app = angular.module('myApp', []);
app.filter('shortName', function() {
return function(x) {
var shortName="", nameTokens=[];
nameTokens = x.split(" ");
nameTokens.forEach(function(token){ shortName+=token[0] });
return shortName;
};
});
app.controller('namesCtrl', function($scope) {
$scope.name = 'John Smith';
});
</script>
</body>

angular
.module('myApp',[])
.run(function($rootScope){
$rootScope.title = 'myTest Page';
})
.controller('testController', ['$scope', function($scope){
$scope.myName = 'saurabh raman';
}]).filter('filter', function() {
return function(input) {
var name = input;
var inls = name.match(/\b\w/g) || [];
inls = ((inls.shift() || '') + (inls.pop() || '')).toUpperCase();
return inls;
}
});
view
<p>{{myName | filter}}</p>
</body>
</html>

I was hoping there was a built-in filter for it, but it seems there isn't one, so I've created this filter:
var relConclusaoApp = angular.module("relatorioConclusaoApp", []);
relConclusaoApp.filter('onlyinitials', [function () {
return function (input) {
if (input) {
return input
.split(/\s+/)
.filter(s => s.length > 2)
.map(s => s.charAt(0).toLocaleUpperCase())
.join(".")
.concat(".")
}
return input;
}
}])
This filter is going to transform Floor Jansen into F.J. (e.g.)
It should be used in your template as:
{{nameToBeTransformed | onlyinitials}}

Related

Angular Filter in AngularJs

var app = angular.module('pixmall', []);
app.controller('myDashboard', function($scope, $http) {
app.filter('myRandom', function() {
return function (input) {
return Math.round(input);
}
});
<div ng-app="pixmall" ng-controller="myDashboard">
<span>{{30.35 | myRandom}}</span>
</div>
I want to use the filter to round the number to the nearest whole number but it is not working, I don't know what is wrong
Separate out the controller and filter, you should not place the filter within the controller code.
DEMO
var app = angular.module('pixmall', [])
app.controller("myDashboard",function($scope){
});
app.filter('myRandom', function() {
return function (input) {
return Math.round(input);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.7/angular.min.js"></script>
<div ng-app="pixmall" ng-controller="myDashboard">
<span>{{30.35 | myRandom}}</span>
</div>

How to find an array object according to given information?

I have an array in AngularJS controller like this:
$scope.persons = [{name:'Joey', age:'27'},{name:'Lucy', age:'22'}]
I have got a name 'Lucy', how can I get the age of the name in the controller (not in HTML)?
I've created a plunk here that outlines a single result, with just the age, as well as multiple results.
This could also be implemented within a filter, which is documented on the Angular site here: https://docs.angularjs.org/api/ng/filter/filter
https://plnkr.co/edit/OFRMzpQrZfTOnaFyJP7Z?p=info
angular.module('plnk',[]).controller('plnkCtrl', function($scope){
// Note, I added a second Joey here to test the multiple function.
// For output, check the browser console.
$scope.persons = [{name:'Joey', age:'27'},{name:'Joey', age:'28'},{name:'Lucy', age:'22'}]
console.log('Single -> ', getAgeSingle('Lucy'));
console.log('Multiple ->',getAgeMultiple('Joey'));
function getAgeMultiple(personLookup) {
var results = [];
angular.forEach($scope.persons,function(person){
if (person.name === personLookup) {
results.push(person);
// or results.push(person.age) for age only
}
});
return results;
}
function getAgeSingle(personLookup) {
var result = '';
angular.forEach($scope.persons,function(person){
if (person.name === personLookup && !result) {
result = person.age;
}
});
return result;
}
});
Just loop over the array and check, like this:
function getAge(name)
{
for (var i = 0; i < $scope.persons.length; i++)
{
var person = $scope.persons[i];
if (person.name === name)
{
return parseInt(person.age, 10);
}
}
return undefined;
}
This has a couple caveats -- if you have dupes you'll only get the first one and it runs in linear time. If you control the data source it'd be better to use a JS object/hashmap/dictionary/whatever you want to call it.
If you wanted to loop through the scope:
$scope.persons = [{name:'Joey', age:'27'}, {name:'Lucy', age:'22'}]
function getAge(name) {
angular.forEach($scope.persons, function (value, index) {
if (value.name === name) {
return parseInt(value.age, 10);
}
});
return undefined;
}
The HTML way:
<div ng-app="myApp" ng-controller="MainCtrl">
<table>
<tr ng-repeat="person in persons">
<td>Name: {{person.name}} Age: {{person.age}}</td>
</tr>
</table>
</div>
JS:
var app = angular.module('myApp', []);
app.controller('MainCtrl', function ($scope) {
$scope.persons = [{name:'Joey', age:'27'}, {name:'Lucy', age:'22'}];
});

split string and numeric in angularjs

i have a string like, "ABCD000215" i need split into string and numeric separately. I need to add break between the string and number
my code
<div class="box-label">{{item.stringVal}}</div>
The result will be like this
ABCD
000215
You can use an Angular filter.
Html:
<body ng-controller="MainCtrl as main">
<div class="box-label">{{main.stringVal | splitStringAndNumber}}</div>
</body>
JS:
var app = angular.module('angularApp', []);
app.controller('MainCtrl', function() {
this.stringVal = "ABCD12334234";
});
app.filter('splitStringAndNumber', function($filter){
return function(string){
var matches = string.match(/\d+|[a-z]+/ig);
return matches.join('\r\n');
};
});
Here's an example: https://plnkr.co/edit/G6ltclPLxRpijruYjcqy?p=preview
Try this
[a-z]+|\d+
Regex demo
Explanation:
+: One or more sample
|: Alternation / OR operand sample
\: Escapes a special character sample
Here Check This Plunker I Created .. Hope this helps :)
var app = angular.module('app', []).filter('checkmark', function() {
return function(input, regex) {
var patt = new RegExp(regex);
var out = [];
for (var i = 0; i < input.length; i++){
if(patt.test(input[i]))
out.push(input[i]);
}
return out;
};
});
app.controller('ctrl',function($scope){
$scope.a = "ABCD000215";
});
<p>Sum: {{a | checkmark : '^[0-9]*$'}}</p>
<p>Sum: {{a | checkmark : '^[a-zA-Z]*$'}}</p>
https://plnkr.co/edit/irKm0idyEy7jglYz5e6R?p=preview

Filter Change the color of the word in the sentence angularjs

I want to change the color of the word in the sentence How can i do that?
Controller code:
app.controller("myController",function($scope){
$scope.phrase="This is a bad phrase";
});
app.filter('censor', function(){
return function(input){
var cWords = ['bad', 'evil', 'dark'];
var out = input;
for(var i=0; i<cWords.length;i++){
out = out.replace(cWords[i], <span class="blue"></span>);
}
return out;
};
})
My view:
{{phrase | censor}}
First of all, if you want to bind html in your filter, you need to use ngSanitize and binding with the directive: ng-bind-html instead of {{ }}, like this:
<p ng-bind-html="ctrl.phrase | censor"></p>
In your js file you need to check if the phrase contain any of the words you want to filter out, then update the phrase.
angular
.module('app', ['ngSanitize'])
.controller('MainCtrl', function() {
var ctrl = this;
ctrl.phrase = 'This is a bad phrase';
})
.filter('censor', function() {
return function(input) {
var cWords = ['bad', 'evil', 'dark'];
var splitPhrase = input.split(' ');
var out = splitPhrase.reduce(function(acc, curr) {
if (cWords.indexOf(curr) > -1) {
acc.push('<span class="blue">' + curr + '</span>');
} else {
acc.push(curr);
}
return acc;
}, []);
return out.join(' ');
}
});
You can find an example here: http://jsbin.com/koxekoq/edit?html,js,output

AngularJS: how to modify an array in the service from multiple controllers

I want to have an array in the service, which can be modified from different controllers.
The purpose of this is the have an array accessible through every controller.
I want to be able to push items to this array from controllers, as well to delete them.
Service:
.service('EmailOps', function () {
var templates = [];
return {
pushToEmailBody: function (newObj) {
templates.push(newObj);
console.log(templates);
}
};
});
Controller:
angular.module('app')
.controller('mainCtrl', function ($scope, $rootScope, EmailOps) {
$scope.include = EmailOps.pushToEmailBody;
});
HTML:
<div ng-controller="mainCtrl">
1
2
3
</div>
To summarize, I would like to be able to add multiple new elements to the array in the service by clicking on these links. Currently when it adds one of them, it replaces the one added before, so that I have an array with one element only. Any idea what I might be doing wrong?
please see here : http://jsbin.com/gesirira/1/edit
service:
app.service('EmailOps', function () {
var templates = [];
function pushToEmailBody (newObj) {
templates.push(newObj);
console.log(templates);
}
return {
templates:templates,
pushToEmailBody : pushToEmailBody
};
});
controller:
app.controller('firstCtrl', function($scope,EmailOps){
$scope.include = function(obj)
{
EmailOps.pushToEmailBody(obj);
};
$scope.temp = EmailOps.templates;
});
html:
<body ng-app="app">
<div ng-controller="firstCtrl">
1
2
3
<br/>
templates: {{temp |json}}
</div>
</div>
</body>
You can modify your service like this
.service('EmailOps', function () {
this.templates = [];
this.pushToEmailBody = function (newObj) {
templates.push(newObj);
console.log(templates);
}
});
and then in the controller :
$scope.include = function(obj)
{
EmailOps.pushToEmailBody(obj);
};

Resources