Array with 2 properties, AngularJs - angularjs

I need to save 2 Strings into an array like this:
array[0].name = "William"
array[0].dni = "00112233Z"
so i can use ng-repeat:
<ul>
<li ng-repeat="item in array">
{{item.name}}
{{item.dni}}
</li>
</ul>
But I don't know how to declare it in Angular, I keep getting this error no matter how i try: TypeError: Cannot set property 'name' of undefined.
Here's the code where I'm getting the data:
$scope.array=[];
$scope.initial = function () {
$http.get('data/people.json').success(function (data) {
$scope.jsonData = data;
for(var i=0; i<$scope.jsonData.persons.length;i++){
$scope.array[i].name=$scope.jsonData.persons[i].person.nombre;
$scope.array[i].dni=$scope.jsonData.persons[i].person.dni;
}
});
};
Any help would be appreciated.
Regards.

You have to set an object first inside the array to assign properties like:
$scope.array=[];
$scope.initial = function () {
$http.get('data/people.json').success(function (data) {
$scope.jsonData = data;
for(var i=0; i<$scope.jsonData.persons.length;i++){
$scope.array[i] = {};
$scope.array[i].name=$scope.jsonData.persons[i].person.nombre;
$scope.array[i].dni=$scope.jsonData.persons[i].person.dni;
}
});
};
Otherwise array[i] is undefined because is an empty array

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>

Why I get error Error: [ngRepeat:dupes] in Angular JS?

I use ng-repeat:
<option ng-selected="key == formData.city" ng-repeat="(key, value) in data.cities | orderBy:value" value="{{key}}">{{value}}</option>
data.cities is array.
Also I have method that gets array of cities from AJAX response and sets it to exists array $scope.data.cities:
request.success(function (data) {
var arr = []
angular.forEach(data.res, function(item) {
arr[item.id] = item.name;
});
$scope.data.cities = arr;
});
Why after response I get error: [ngRepeat:dupes]?
You have to use track by $index with your ng-repeat to avoid duplicates:
ng-repeat="(key, value) in data.cities track by $index | orderBy:value"
https://docs.angularjs.org/error/ngRepeat/dupes
Update:
You memory leak might be a reason of using array:
var arr = [];
For example, if your cities.id looks like 1001 this will produce an array with 1000 empty items and one with your city.
In your situation I would recommend to use an Object instead of Array:
request.success(function (data) {
var obj = {};
angular.forEach(data.res, function(item) {
obj[item.id] = item.name;
});
$scope.data.cities = obj;
});
Also, you can replace ng-repeat with ng-options here:
<select ng-model="formData.city" ng-options="key as value for (key, value) in data.cities">

Get model array values in controller's service

I've been facing an issue since couple of hours. My view template looks like-
<div class="row" ng-repeat="row in CampaignsService.getRows().subItems track by $index">
<div class="col-sm-2">
<select class="form-control dropDownPercent" ng-model="CampaignsService.dropDownPercent[{{CampaignsService.selectCounter}}]" ng-change="CampaignsService.wow(CampaignsService.dropDownPercent, $index)" ng-options="o as o for o in CampaignsService.showPercentDropDown().values">
</select>
</div>
<div class="col-sm-2" style="line-height: 32px">
of visitors send to
</div>
<div class="col-sm-4">
<select class="form-control" ng-model="campaignSelect" ng-options="campaign.Campaign.id as campaign.Campaign.title for campaign in CampaignsService.getRows().items">
<option value=""> Please select </option>
</select>
</div>
<div class="col-sm-4">
<a class="btn btn-default" target="_blank" href="">Show campaign</a>
</div>
Variable CampaignsService.selectCounter is a counter variable and declared in service but when I'm going to use ng-model="CampaignsService.dropDownPercent[{{CampaignsService.selectCounter}}]" it gives me error -
Error: [$parse:syntax] Syntax Error: Token '{' invalid key at column 35 of the expression [CampaignsService.dropDownPercent[{{CampaignsService.selectCounter}}]] starting at [{CampaignsService.selectCounter}}]]
And when I use ng-model="CampaignsService.dropDownPercent['{{CampaignsService.selectCounter}}']" it does not give any error but it takes this variable as string.
My question is how could I create a model array and get model's array values in my service ?? I read many questions in stack community and none of the trick work for me. My service under my script, is
.service('CampaignsService', ['$rootScope', 'AjaxRequests', function ($rootScope, AjaxRequests) {
this.dropDownPercent = [];
this.selectCounter = 0;
var gareeb = [];
this.showPercentDefault = 100;
// this.campaignsData = [];
this.$rowsData = {
items: [], //array of objects
current: [], //array of objects
subItems: [] //array of objects
};
this.getRows = function () {
return this.$rowsData;
}
this.addNewRow = function () {
var wowRow = {}; //add a new object
this.getRows().subItems.push(wowRow);
this.selectCounter++;
gareeb.push(0);
}
this.calculatePercentages = function (index) {
angular.forEach(this.getRows().current, function (data, key) {
if (key == index) {
console.log(data);
}
})
}
this.showPercentDropDown = function ($index) {
var balle = 0;
var start;
angular.forEach(gareeb, function (aha, keywa) {
balle += aha;
})
var last = 100 - balle;
var final = [];
for (start = 0; start <= last; start += 10) {
final.push(start);
}
return this.values = {
values: final,
};
}
this.wow = function (valueWa, keyWa) {
console.log(this.dropDownPercent);
gareeb[keyWa] = valueWa;
this.changePercentDropDown();
}
this.changePercentDropDown = function () {
var angElement = angular.element(document.querySelector('.dropDownPercent'));
angular.forEach(angElement, function (data, key) {
console.log(data);
})
}
}])
Target model structure should be
ng-model="CampaignsService.dropDownPercent[1]"
ng-model="CampaignsService.dropDownPercent[2]"
ng-model="CampaignsService.dropDownPercent[3]"
A big thanks in advance.
Since you are in context of the Angular expression, you don't need interpolation tags {{...}}. So ngModel directive should look like this:
ng-model="CampaignsService.dropDownPercent[CampaignsService.selectCounter]"

Angularjs "this" is undefined in normal object

I am creating a quiz in angular and i use this code:
<ul>
<li ng-repeat="choice in choices" class="choices" ng-click="setSelection(choice)">{{choice}}</li>
</ul>
var choiceSelection = {
isSelected: false,
userAnswers: [],
setSelection: function(choice) {
this.userAnswers.push(choice);
console.log(this.userAnswers);
}
};
$scope.setSelection = choiceSelection.setSelection;
I want to store the users choice in the userAnswers array, but the this in setSelection is undefined and therefore this.userAnswers nor this.isSelected works. This code works in normal JS, I just tested it.
What's going on here?
You could bind the proper value for this to your setSelection function:
var choiceSelection = new function ( ) {
this.isSelected = false;
this.userAnswers = [];
this.setSelection = function(choice) {
this.userAnswers.push(choice);
console.log(this.userAnswers);
}.bind( this );
} ;
$scope.setSelection = choiceSelection.setSelection;

AngularJS: nested array and view update

I'm having problems updating the view after an Array inside an Array is updated in the $scope.
First i check if the Array member already exists:
$scope.myArray = [];
if(typeof $scope.myArray[someIndex] == 'undefined') {
$scope.myArray[someIndex] = {
name: someName,
data: []
};
}
Then push to $scope.myArray[someIndex].data:
$scope.myArray[someIndex].data.push(dataContent);
At this point the view does not update.
Of course if i directly push to $scope.myArray it does. Any suggestions?
Edit: Fiddle here
It was simpler than it looked.
Based on the response here i am setting an associative array which allows set string keys. If you declare your array as =[] you simply cannot set strings as keys.
So i just changed my declaration $scope.myArray=[] to $scope.myArray={} and voilĂ , it works.
Try:
if(typeof $scope.myArray[someIndex] == 'undefined') {
$scope.$eval(function(){
$scope.myArray[someIndex] = {
name: someName,
data: []
};
$scope.myArray[someIndex].data.push(dataContent);
});
}
This works:
HTML,
<div ng-app>
<div ng-controller="NestedCtrl">
<article ng-repeat="member in myArray">
{{member.name}}
<article ng-repeat="next in member.data">
{{next.nested}}
</article>
</article>
</div>
</div>
Angular JS:
function NestedCtrl($scope) {
$scope.myArray = [];
var callMe = function(){
if(typeof $scope.myArray[0] == 'undefined') {
$scope.myArray[0] = {
name: 'Hello',
data: []
};
}
$scope.myArray[0].data.push({nested : 'yay'});
}
callMe();
}

Resources