While lower than value - angularjs

Say I have a variable x with a value of 7, I need to echo out this html
{{y}}
Where y is 1,2,3... until y == x. How do I do this in Angular?

Using this answer you can create a filter which does this for you:
HTML
<div ng-app='myApp' ng-controller="Main">
{{y}}
</div>
Controller
var myApp = angular.module('myApp', []);
function Main($scope){
$scope.range = function(min, max){
var input = [];
for (var i=min; i<=max; i++) input.push(i);
return input;
};
};
JSFiddle

Related

How to wrap this controller logic inside a angular function and use it in select html element

How to wrap this controller logic inside a angular function and use it in select html element. Here inside controller code is use as inline logic without function.
Controller:
var year = new Date().getFullYear();
var range = [];
range.push(year);
for(var i=1;i<20;i++) {
range.push(year + i);
}
$scope.years = range;
View:
<select ng-options="year for year in years">
</select>
You can declare a function like that :
$scope.myfunction = function(){
var year = new Date().getFullYear();
var range = [];
range.push(year);
for(var i=1;i<20;i++) {
range.push(year + i);
}
return range;
}
and in your HTML :
<select ng-model="selectedYear" ng-options="year for year in myfunction()"></select>
I think all you are missing is the ng-model from the select statement. Here is a working example:
(function() {
angular
.module("app", []);
angular
.module("app")
.controller("AppController", AppController);
AppController.$inject = ["$scope"];
function AppController($scope) {
var vm = this;
vm.selectedYear = "";
vm.years = [];
loadData();
function loadData() {
var year = new Date().getFullYear();
var range = [];
range.push(year);
for (var i = 1; i < 20; i++) {
range.push(year + i);
}
vm.years = range;
}
}
})();
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="angular.js#1.6.1" data-semver="1.6.1" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="AppController as vm">
<div>
<select ng-model="vm.selectedYear"ng-options="year for year in vm.years">
</select>
</div>
</body>
</html>

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

Angular - ngOptions model value not updating

Getting started with Angular and am having an issue getting the model binding to work for a select option in a template.
I have the following ng-options select in a template:
<select ng-model="listenercount" ng-options="n for n in [] | range:0:1000" ng-change="listenersUpdate()"></select>
I have filter which looks like this:
angular.module('myapp').filter('range', function() {
return function(input, min, max) {
min = parseInt(min);
max = parseInt(max);
for (var i=min; i<max; i++) {
input.push(i);
}
return input;
};
});
My select shows up correctly with options 0-1000 based on my filter.
In my controller I have the following:
$scope.listenercount = 0;
$scope.listenersUpdate = function() {
alert('new listener count is now:' + $scope.listenercount);
}
My alert message pops up every time I change the select as expected, but it always show $scope.listenercount = 0. The $scope.listenercount model binding does not seem to be update the value.
Anything obvious I am doing wrong?
<body ng-app="myapp">
<script>
angular.module('myapp', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.listenercount = 0;
$scope.listenersUpdate = function() {
alert('new listener count is now:' + $scope.listenercount);
}
}]);
angular.module('myapp').filter('range', function() {
return function(input, min, max) {
min = parseInt(min);
max = parseInt(max);
for (var i=min; i<max; i++) {
input.push(i);
}
return input;
};
});
</script>
<div ng-controller="ExampleController">
<select ng-model="listenercount" ng-options="n for n in [] | range:0:1000" ng-change="listenersUpdate()"></select>
<tt>debug = {{confirmed}}</tt><br/>
<tt>counter = {{counter}}</tt><br/>
</div>
</body>
This is working as expected

the diffrence between angular.foreach and "for"

I tried the Todo Example in Angular home page (No.2) and modified a little code which cause a wired problem.
When I add two Todo, the dispaly is ok which is displayed as “4 of 4 remain [archive]”,then I select 2 Todo item and click "acrhive". The result should be “2 of 2 remain [archive]", but acctually the display is “2 of 4 remain [archive]".
Then I replace ”for“ loop wiht "angular.forEach" function, the result is correct.
So anyone can explain what is the diffrence when I use between "for loop" and "angular.forEach"?
The coding is shown as belowing:
<html>
<head>
<meta charset="utf8">
<script src="js/angular.js"></script>
</head>
<body ng-app ng-controller="ToDo">
<span>{{remains()}} of {{total}} remain</span><span>[archive]</span>
<ul>
<li ng-repeat="todo in todos">
<input type="checkbox" ng-model="todo.checked">{{todo.item}}
</input>
</li>
<form ng-submit="addTodo()">
<input type="text" ng-model="toDoitem" placeholder="add Todo List here"></input>
<span><input class="btn-primary" type="submit" value="Add"></input></span>
</form>
</ul>
<script>
var ToDo = function ($scope) {
$scope.todos = [
{item:"Discuss with my team",checked:false},
{item:"Mail to Jack",checked:false}
];
$scope.total = $scope.todos.length;
$scope.remains = function() {
var count =0;
for (var i=0;i<$scope.todos.length;i++) {
count += $scope.todos[i].checked?0:1
};
return count;
};
$scope.action= function($index) {
$scope.todos[$index].checked=!todos[$index].checked
$scope.remain += todos[$index].checked?-1:1;
};
$scope.addTodo = function() {
$scope.total ++;
$scope.todos.push({item:$scope.toDoitem,checked:false});
$scope.toDoitem = '';
};
$scope.archive = function() {
var oldTodos = $scope.todos;
$scope.todos = [];
for (var i=0;oldTodos.length-1;i++){
if (!oldTodos[i].checked) {
$scope.todos.push({item:oldTodos[i].item,checked:false});
};
};
/*
angular.forEach(oldTodos,function(todo){
if (!todo.checked) {
$scope.todos.push(todo);
};
});
*/
$scope.total = $scope.todos.length;
};
};
//http://jsfiddle.net
//http://plnkr.co/
</script>
</body>
</html>
In the context of your example there is nothing in particular different between angular.forEach and a standard for loop.
You don't appear to be pushing the same object into $scope.todos in the forEach, does the following help:
angular.forEach(oldTodos, function(todo) {
if (!todo.checked) {
$scope.todos.push({item: todo.item, checked: false});
};
});
You just need to have a look at the implementation for forEach for arrays and compare it with yours:
Angularjs forEach implementation for arrays:
for (key = 0; key < obj.length; key++)
iterator.call(context, obj[key], key);
And yours:
for (var i=0;oldTodos.length-1;i++){
if (!oldTodos[i].checked) {
$scope.todos.push({item:oldTodos[i].item,checked:false});
};
};
You could try:
for (var i=0; i < oldTodos.length; i++){
if (!oldTodos[i].checked) {
$scope.todos.push({item:oldTodos[i].item,checked:false});
};
};

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