Why my splice or push its not working with AngularJS - angularjs

I am trying to do an update for an array and i have to splice first that element and then make a push. That list I am using it in a HTML file, where i am using an ng-repeat.
vm.editTemplate=function() {
var selectedTemplate = localStorage.getItem("selectedTemplate");
localStorage.removeItem("selectedTemplate");
$mdDialog.show({
controller: 'EditTemplateCtrl',
controllerAs: 'template',
templateUrl: 'views/templatess/addTemplate.html',
locals: {
template:selectedTemplate
}
})
.then(function() { },
function(item) {
console.log(item);
console.log($scope.templatesArray);
for (var i = 0; i < $scope.templatesArray.length; i++) {
if (item.id == $scope.templatesArray[i].id) {
$scope.templatesArray.splice(i,1);
}
}
});
}
in my HTML file i have this
<div class="hover"
ng-repeat="list in templatesArray"
ng-click="temp.selectUser(list)"
ng-class="{'active': temp.selectedRow.id == list.id}"
style=" cursor:pointer;border-bottom:1px solid #fff; margin-bottom:0;"
layout-align="space-around center"
layout="row">
<span flex="5"></span>
<span id="{{list.id}}" flex="90" ng-click="temp.selectTemplate(list)">
{{list.description}}
</span>
<span flex="5"></span>
</div>

Don't think it's good to do a splice inside a loop on the same array.
Furthermore, as already mentioned here, you should assign the results of splice.
So I would rather do:
1. Find the index, something like following (or with the help of a
library like underscore.js to avoir to write your own loop)
var index = -1;
for (var i = 0; i < $scope.templatesArray.length; i++) {
if (item.id==$scope.templatesArray[i].id) {
index = i;
}
}
2. Then splice
if (index > -1) {
$scope.templatesArray = $scope.templatesArray.splice(index,1);
}

Related

Compare two arrays and concat without duplicates

I have two arrays. I can push and splice by clicking on a word in searchWords, which adds or removes a word to the currentWordlist.
What I want to have is a button that transfers all the searchWords to the currentWordlist, without overwriting the words that are actually on the currentWordlist.
I came up with this code:
$scope.addAll = function () {
var searchWords = [];
var currentWords = [];
// safes all searchwords to the array
for (var i = 0; i < $scope.searchWords.length; i++) {
searchWords.push($scope.searchWords[i]);
}
// safes all currentwords to the array
for (var j = 0; j < $scope.currentWordlist.length; j++) {
currentWords.push($scope.currentWordlist[j]);
}
console.log("searchWords " + searchWords.length);
console.log("currentWords " + currentWords.length);
angular.forEach(searchWords, function(value1, key1) {
angular.forEach(currentWords, function(value2, key2) {
if (value1._id !== value2._id) {
$scope.currentWordlist.push(value1);
}
});
});
};
I go through both of the arrays and safe them so that I can use the arrays inside my two angular.forEach to check if there are duplicates. If I don't push to the currentWordlist. But it's not working. I get an [ngRepeat:dupes] error, but I cannot use track by $index because otherwise removing from the list removes the wrong word. I think I am doing something critically wrong here, but I couldn't find out what so far (hours of trial and error :0)
I would suggest to use angular unique filter with ng-repeat directive. The code could be as follows:
$scope.addAll = function () {
// use angular.copy to create a new instance of searchWords
$scope.combinedWords = angular.copy($scope.searchWords).concat($scope.currentWordlist);
};
And then in your view:
<div ng-repeat="word in combinedWords | unique:'_id'">
{{word}}
</div>
Usage:
colection | uniq: 'property'
It also possible to filter by nested properties:
colection | uniq: 'property.nested_property'
You can simply do like this
angular.forEach($scope.searchWords, function(value1, key1) {
var temp=true;
angular.forEach($scope.currentWordlist, function(value2, key2) {
if (value1.id === value2.id)
temp=false;
});
if(temp)
$scope.currentWordlist.push(value1);
});
var app = angular.module("app", []);
app.controller("ctrl", function($scope) {
$scope.searchWords=[{id:1,name:'A'},{id:2,name:'B'},{id:1,name:'A'},{id:4,name:'D'}];
$scope.currentWordlist=[];
$scope.addAll = function() {
angular.forEach($scope.searchWords, function(value1, key1) {
var temp=true;
angular.forEach($scope.currentWordlist, function(value2, key2) {
if (value1.id === value2.id)
temp=false;
});
if(temp)
$scope.currentWordlist.push(value1);
});
console.log($scope.currentWordlist);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<button ng-click="addAll(newWord)">Add</button>
<div>{{currentWordlist}}</div>
</div>

How to "connect" 2 variables in Angular by some value

I have 2 variables in controller:
$scope.first = [
{ id="11", nameF="aaaa1" },
{ id="12", nameF="bbbb1" }
]
$scope.second = [
{ id="21", nameS="aaaa2", idFirst="11" },
{ id="22", nameS="bbbb2", idFirst="12" },
{ id="23", nameS="cccc2", idFirst="12" }
]
In a template I have ngRepeat for variable second:
<div ng-repeat="item in second>
<div>{{item.nameS}}</div>
<div>{{item.idFirst}}</div>
</div>
For every item.idFirst I would like to write out matching nameF instead. What is the best practice to achieve that? I can't seem to figure out a simple way to do it, but suppose there has to be one. Thanx!
You can use custom filter if you don't want to create one single object holding the expected structure.
HTML :
<div ng-repeat="item in second">
<div>{{item.nameS}}</div>
<div>{{item.idFirst | getMatchName:first}}</div>
</div>
JS:
.filter('getMatchName', function() {
return function(strName, arrFirst) {
arrFirst.forEach(function(val, key) {
if (val.id == strName) {
strName = val.nameF;
}
})
return strName;
}
})
Here is working plunker
If I understand correctly,
$scope.getNameF = function(idFirst){
for(var i = 0; i < $scope.first.length; i++){
if($scope.first[i].id === idFirst){
return $scope.first[i].nameF;
}
}
return undefined;
}
<div ng-repeat="item in second">
<div>{{item.nameS}}</div>
<div>{{getNameF(item.idFirst)}}</div>
</div>
EDIT
Also you can prepare data before rendering:
for(var i = 0; i < $scope.second.length; i++){
$scope.second[i].nameF = getNameF($scope.second[i].idFirst);
}
<div ng-repeat="item in second">
<div>{{item.nameS}}</div>
<div>{{item.nameF}}</div>
</div>
You can think of your template logic a bit like code, calling values from other variables: yourValue[another.value].nameF
Change your code to this and it should work
<div ng-repeat="item in second>
<div>{{item.nameS}}</div>
<div>{{first[item.idFirst].nameF}}</div>
</div>

Can't find Element Inside Template with querySelectorAll

Im done with visual things of my proj. Now, trying to put template tags. But my 'click toggle' event isnt working now. Tried lots of solutions. At the same time you may give hints about polymer.
Putted template tags like this:
<template is="dom-if" if="{{isUnis(tabSelected)}}">
<template is="dom-repeat" items="{{unis}}">
<paper-icon-item u="{{item.name}}">
<iron-image src="{{unImg(item.name)}}" sizing="contain" style="width:32px;height:32px" item-icon fade preload></iron-image>
<div class="flex">{{item.name}}</div>
<span>1</span>
</paper-icon-item>
</template>
</template>
<template is="dom-if" if="{{isDers(tabSelected)}}">
<paper-icon-item u="İstanbul">
<iron-image src="/unis/uni/istanbul.png" sizing="contain" style="width:32px;height:32px" item-icon fade preload></iron-image>
<div class="flex">İstanbul</div>
<span>1</span>
</paper-icon-item>
</template>
And my script inside template:
var notarApp = Polymer.dom(document).querySelector('notar-app');
document.addEventListener('polymer-ready', function() {
var p = Polymer.dom(notarApp.root).querySelectorAll('paper-icon-item'),
sifir = 0,
buyuttu = document.getElementById('#buyuttu'),
selected = document.getElementById('#selected');
for (var i = 0; i < p.length; i++) {
p[i].addEventListener('click', function() {
this.classList.toggle('shadow-2');
var listme = [];
for (var j = 0; j < p.length; j++) {
if (!(hasClass(p[j], 'shadow-2'))) {
continue;
}
listme.push(" " + p[j].attributes[0].nodeValue);
selected.innerHTML = listme;
}
if (listme.length == 0) {
selected.innerHTML = 'Listelemek için üniversite ve/ya ders seçin';
}
if (sifir == 0 && listme.length > 4) {
buyuttu.show();
sifir++;
}
});
}
});
Last i tried this inside polymer-ready and nothing happened:
if(p.length) {
console.log(p);
}
My guess is dom-if doesnt load content when if state is false.

ng-repeat pagination looses items

I'm learning AngularJS following the good Pro AngularJS written by Adam Freeman.
I'm stuck on ng-repeat pagination using filters. I know there are bootstrap ui directives for Angular, but i'm following this book in order to learn how angular works.
My code:
<section class="row-fluid" ng-controller="GetAjax">
<div class="col-md-12">
<h2>Repater Caricato in Ajax</h2>
</div>
<div class="row-fluid">
<div class="col-md-6" style="max-height: 350px; overflow-y: auto" ng-controller="PagedData">
<ul class="list-group">
<li class="list-group-item" ng-repeat="item in data.visitors | filter:query | range:selectedPage:pageSize">
<b>{{item.id}}.</b> {{item.first_name}} {{item.last_name}} | <small><i>{{item.email}} - {{item.country}} {{item.ip_address}}</i></small>
</li>
</ul>
<ul class="pagination">
<li ng-repeat="page in data.visitors | pageCount:pageSize"
ng-click="selectPage($index + 1)"
ng-class="pagerClass($index + 1)">
<a>{{$index + 1}}</a>
</li>
</ul>
</div>
</div>
</section>
Angular filters
angular.module("customFilters")
/******* Filters per la paginazione dei dati ******************/
//Genera il range di dati in base alla page size
.filter("range", function ($filter) {
return function (data, page, size) {
if (angular.isArray(data) && angular.isNumber(page) && angular.isNumber(size)) {
var start_index = (page - 1) * size;
console.log(data.length);
if (data.length < start_index) {
return [];
} else {
return $filter("limitTo")(data.splice(start_index), size);
}
} else {
return data;
}
}
})
//Calcola il numero di pagine
.filter("pageCount", function () {
return function (data, size) {
if (angular.isArray(data))
{
var result = [];
for (var i = 0; i < Math.ceil(data.length / size) ; i++) {
result.push(i);
}
return result;
}
else
{
return data;
}
}
});
Angular Controller
.controller("GetAjax", function($scope, $http){
$http.get('data/visitors.json').success(function(data) {
$scope.data = {visitors : data};
});
})
.constant("activeClass", "active")
.constant("perPage", 30)
.controller("PagedData", function($scope, $filter, activeClass, perPage){
$scope.selectedPage = 1;
$scope.pageSize = perPage;
console.log("page"+ $scope.selectedPage);
$scope.selectPage = function (newIndex) {
$scope.selectedPage = newIndex;
console.log( {idx: newIndex});
}
$scope.pagerClass = function (index) {
return (index == $scope.selectedPage) ? activeClass : "";
}
});
The result is that after 3 range filter invocations during the page render, the data array looses all the data.
Strange is that using the example from the book this code works perfectly.
Please, help me to know my error :D
splice function overwrites array
if you have an array
a = [1,2,3,4];
a.splice(2,1);
// a = [1,2,4]
results is a = [1,2,4]
use slice instead

Moving angularJS elements created by ng-repeat

I'm trying to move elements that are created by a ng-repeat into some columns. I successfully did it with a directive, but the problem happens when I sort the array of objects on which ng-repeat operates. The directive that searches for the smallest column and then insert the element in it fails to determine the smallest column (maybe because there are still elements in the columns).
I believe the structure I use (directives / controllers etc...) isn't optimal, and I cannot find how to organize the angular code to get the behavior I want.
Here is a jsFiddle showing what I have now : http://jsfiddle.net/kytXy/6/ You can see that the items are being inserted correctly inside the columns. If you click on a button that re-arranges the sorting, then they are not inserted again. If you click multiple times on a same button, watch what happens...
I put commented alerts that you can uncomment so that you can see how items are being inserted and what is wrong. I've also tried emptying the columns before inserting again (commented js in the jsfiddle), whithout any success.
Here is the code :
HTML:
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<div ng-app="myModule">
<div ng-controller="Ctrl" >
<button ng-click="predicate = 'id'; reverse=false; setupColumns()">Sort ID</button>
<button ng-click="predicate = 'id'; reverse=true; setupColumns()">Sort ID reversed</button>
<div id="columns" generate-sub-columns post-render>
</div>
<div class="elements">
Elements are stored here !
<div class="element" ng-repeat="(key,elt) in elts | orderBy:predicate:reverse" id="element{{key}}">
Text: {{elt.a}}
</div>
</div>
</div>
</div>
JS:
var myModule = angular.module('myModule', []);
myModule.controller('Ctrl', function($scope) {
$scope.predicate='id';
$scope.reverse=false;
$scope.elts = [
{id:0,a:"Hi man !"},
{id:1,a:"This is some text"},
{id:2,a:"Wanted to say hello."},
{id:3,a:"Hello World!"},
{id:4,a:"I love potatoes :)"},
{id:5,a:"Don't know what to say now. Maybe I'll just put some long text"},
{id:6,a:"Example"},
{id:7,a:"Example2"},
{id:8,a:"Example3"},
{id:9,a:"Example4"},
{id:10,a:"Example5"},
{id:11,a:"Example6"}
];
$scope.setupColumns = function() {
console.log('calling setupColumns');
var eltIndex = 0;
var element = jQuery("#element0");
/*while(element.length > 0) {
jQuery('#elements').append(element);
eltIndex++;
element = jQuery("#element"+eltIndex);
alert(1);
}
alert('Columns should be empty');*/
element = jQuery("#element0");
eltIndex = 0;
var columnCount = 0;
while (jQuery("#column"+columnCount).size() >0)
columnCount++;
while(element.length > 0) {
console.log('placing new element');
var smallestColumn = 0;
var smallestSize = jQuery("#columns").height();
for (var i = 0; i < columnCount; i++) {
var columnSize = jQuery(".column#column"+i).height();
if (columnSize < smallestSize) {
smallestColumn = i;
smallestSize = columnSize;
}
};
jQuery('.column#column'+smallestColumn).append(element);
eltIndex++;
element = jQuery("#element"+eltIndex);
//alert(1);
}
//alert('Columns should be filled');
};
});
myModule.directive('generateSubColumns', function() {
return {
restrict: 'A',
controller: function() {
var availableWidth = jQuery("#columns").width();
var sizePerColumn = 100;
var nbColumns = Math.floor(availableWidth/sizePerColumn);
if (nbColumns<=1)
nbColumns=1;
for (var i = 0; i < nbColumns; i++) {
jQuery('<div class="column" id="column'+i+'">Column '+i+'</div>').appendTo('#columns');
};
}
};
});
myModule.directive('postRender', [ '$timeout', function($timeout) {
var def = {
restrict: 'A',
terminal: true,
transclude: true,
link: function(scope, element, attrs) {
$timeout(scope.setupColumns, 0);
}
};
return def;
}]);
and some css:
#columns {
width: 100%;
}
.column {
width: 100px;
display:inline-block;
vertical-align: top;
border: 1px solid black;
}
.element {
border: 1px solid red;
}
How can I fix that ?
Thanks in advance,
hilnius
First.. Why you are doing something like this?
var element = jQuery("#element0");
Inside a controller?
That kind of code (DOM manipulation) should go inside link function directive and use the $element parameter to access to DOM element.
Also.. What if you use the column-count property to divide your container? https://developer.mozilla.org/es/docs/Web/CSS/column-count

Resources