split string and numeric in angularjs - 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

Related

how to add values dynamically to array in angularjs

I am using angularjs, I have one for loop and I get the loop values into one variable called Name .Now my need is that variable should store into scope array selection . How to achieve this.
code:
$scope.selection = [];
for(var i=0 ;i<$scope.Streams.length;i++)
{
var Name=$scope.Streams[i].Name;
}
here i add the dynamic value of name into scope array.
I need output of my scope variable like this
Guess you want to add items of $scope.Streams to $scope. selection.
you can use Array.push.
$scope.selection = [];
// option1
for(var i=0 ;i<$scope.Streams.length - 1;i++) {
$scope.selection.push($scope.Streams[i]);
}
// option2 (with new instance)
$scope.selection = $scope.Streams.slice();
// option3
$scope.selection = $scope.Streams;
Try this single line of code with Array.map() method :
$scope.selection = $scope.Streams.map(item => { return {"Name":item.Name} });
DEMO
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function($scope) {
$scope.Streams = [
{
"id":1,
"Name":"stream1"
},
{
"id":2,
"Name":"stream2"
},
{
"id":3,
"Name":"stream3"
}
];
$scope.selection = $scope.Streams.map(item => { return {"Name":item.Name} });
console.log($scope.selection);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
</div>

Substr in angularJS to fetch the initials of the full name

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}}

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'}];
});

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: loop through an array crossing values with another array in a view

I am struggling with the following. I have a global array1 with the values FileA, FileB, FileC, FileD and FileE. Then I have a specific array2 with the values FileA and FileC.
The output I would want is something like
<div class="matched">FileA</div>
<div class="not_matched">FileB</div>
<div class="matched">FileC</div>
<div class="not_matched">FileD</div>
<div class="not_matched">FileE</div>
I was thinking in a nested ng-repeat with a custom filter, but I am not able to see how to do it.
Here it is an attempt that is not even compiling
html
<body ng-app="myModule">
<div ng-controller="myController">
<div ng-repeat="entity in entities">
<div ng-repeat="myEntity in myEntities | lookInside(entity)">
{{myEntity.match}} - {{myEntity.name}}
</div>
</div>
</div>
</body>
and js
var myModule = angular.module('myModule', []);
myModule.controller('myController', ['$scope', function($scope) {
$scope.entities = ['fileA', 'fileB', 'fileC', 'fileD', 'fileE'];
$scope.myEntities = ['fileA', 'fileC'];
}]);
myModule.filter('lookInside', function(){
return function(items, name){
var arrayToReturn = [];
var name = {};
for (var i=0; i<items.length; i++){
name.match = 'no';
name.name = items[i];
if (items[i] == name) {
name.match = 'si';
}
arrayToReturn.push(name);
}
return arrayToReturn;
};
});
http://jsfiddle.net/C5gJr/46/
What's the best approach to follow here?
Cheers
UPDATE:
I've solved just by using a filter for each entry that checks if it is inside the array
<body ng-app="myModule">
<div ng-controller="myController">
<div ng-repeat="entity in entities">
{{entity | lookInside: myEntities}}
</div>
</div>
</body>
and js
var myModule = angular.module('myModule', []);
myModule.controller('myController', ['$scope', function($scope) {
$scope.entities = ['fileA', 'fileB', 'fileC', 'fileD', 'fileE'];
$scope.myEntities = ['fileA', 'fileC'];
}]);
myModule.filter('lookInside', function(){
return function(item, array){
var name = 'no';
for (var i=0; i<array.length; i++){
if (array[i] == item) {
name = 'si';
}
}
return name;
};
});
http://jsfiddle.net/C5gJr/48/
However, the impact in the performance of the data processing is very high (large lists of data). This may be unavoidable, but any comment on that is very well welcomed.
Cheers
If all you need to do is switch a class based on the other array, try using ng-class and a scope function to check the secondary array.
http://jsfiddle.net/VrB3H/
<div ng-repeat="entity in entities" ng-class="{'matched': isMatch(entity), 'not_matched': !isMatch(entity)}">
{{isMatch(entity)}} - {{entity}}
</div>
myModule.controller('myController', ['$scope', function($scope) {
$scope.entities = ['fileA', 'fileB', 'fileC', 'fileD', 'fileE'];
$scope.myEntities = ['fileA', 'fileC'];
$scope.isMatch = function(entity)
{
return $scope.myEntities.indexOf(entity) >= 0;
}
}]);
Updated in the question, solved in an easy_to_understand code (IMO), but with a high impact in the perfomance of my code (large lists of data). Any improvement in this sense is very well welcomed

Resources