I am using angular.forEach to iterate over an array and for each value in the array, I am using a GET/ to retrieve it's name (array contains key), then push that name into another array. This new array is being used in a dropdown box (ngOptions).
The issue I am having is that the drop down is being created before the GET/ responses have arrived, so it just displays blank options, then when they arrive it displays all options in each drop down.
I have the following code:
angular.forEach($scope.pots, function(value, key) {
$scope.selections = [];
angular.forEach(value, function(val, ky) {
if (ky === "selections") {
angular.forEach(val, function(v, k) {
$http.get('/selections/' + v).then(function(response) {
var response = response.data;
$scope.selection = response[0];
$scope.selectionName = $scope.selection.name;
$scope.selections.push({name : $scope.selectionName});
value["selectionNames"] = $scope.selections;
})
})
}
})
value["selectionNames"] = $scope.selections;
console.log(value);
So I am iterating over a list of pots which contains a list of selections, using the GET/ to get a list of names based on the list of selections and finally pushing that into the pot's scope. I am resetting the selection after each pot.
What's causing the issue is that reponses all come at once, and they bypass the $scope.selections = []; code, so it just pushes into each pot the complete array from all three pots.
Any tips/advice please? Thank you.
So looks like I've fixed it... Can someone confirm that this is good practice please? I'm basically recreating $scope.selections each time I iterate based on the selectionNames value in the pot (value).
angular.forEach($scope.pots, function(value, key) {
$scope.selections = [];
angular.forEach(value, function(val, ky) {
if (ky === "selections") {
angular.forEach(val, function(v, k) {
$http.get('/selections/' + v).then(function(response) {
$scope.selections = [];
var response = response.data;
$scope.selection = response[0];
$scope.selectionName = $scope.selection.name;
var currentSelections = value.selectionNames;
angular.forEach(currentSelections, function(csV, csK) {
$scope.selections.push(csv);
})
$scope.selections.push({name : $scope.selectionName});
value["selectionNames"] = $scope.selections;
})
})
}
})
value["selectionNames"] = $scope.selections;
console.log(value);
Related
I have a json array object $scope.products= []; and ng-click function called
addRow.
I want to perform a check before push new row to array is new row is already exists in array, or not when addRow function is called.
If it already exists, then new row is not push to array.
$scope.addRow = function(){
$scope.products.push({'pro_name':$scope.pro_name,'pro_id':$scope.pro_id, 'batch_no': $scope.input_batch_no });
}
Since you have a unique identifier you can check whether the list of added rows includes such element with this identifier.
$scope.addRow = function(product) {
if($scope.selectedProducts.find(p => p.pro_id === product.pro_id)) {
return;
};
$scope.selectedProducts.push(product);
}
Here's a working piece of code
Just Check if it exists already in the array:
$scope.addRow = function(){
var exists = false;
$scope.products.forEach(product => {
if (product.pro_name === $scope.pro_name && product.pro_id === $scope.pro_id && product.batch_no === $scope.batch_no) {
exists = true;
}
})
if (!exists) {
$scope.products.push({
'pro_name':$scope.pro_name,
'pro_id':$scope.pro_id,
'batch_no': $scope.input_batch_no
});
}
}
I'm trying to change text elements in a page based on numerical values I pass back from my server. I manage to store each reference as well as the value from the server, but when trying to access to the text value of the object I get hit with the error statusText[key].text is not a function. is it possible to access the object properties when referencing from a list? Javascript and Angular are not my strong suits.
Here's the code:
var log = [];
var statusText = [];
$http.post("url", {userid: currentUserID})
.then(function(response)
{
angular.forEach(response.data.status, function(value, key){
this.push(value.complete);
}, log);
angular.forEach(document.getElementsByClassName("step-status"), function(value, key)
{
this.push(value)
}, statusText);
angular.forEach(statusText, function(value, key)
{
if (log[key] == 2)
{
statusText[key].text('Completed');
}
else if (log[key] == 1)
{
statusText[key].text('In progress');
}
else
{
statusText[key].text('Not started');
}
});
});
Try this
var log = [];
var statusText = [];
$http.post("url", {userid: currentUserID})
.then(function(response)
{
angular.forEach(response.data.status, function(value, key){
this.push(value.complete);
}, log);
angular.forEach(document.getElementsByClassName("step-status"), function(value, key)
{
this.push(value)
}, statusText);
angular.forEach(statusText, function(value, key)
{
if (log[key] === 2)
{
statusText[key] = 'Completed';
}
else if (log[key] === 1)
{
statusText[key] = 'In progress';
}
else
{
statusText[key] = 'Not started';
}
});
});
Sollution: Changed my approach for displaying the returned strings. Just set each element of the array to the string I want and used bindings to display the data.
Thanks for the help all.
(was not sure what to have as a title, so if you have a better suggestion, feel free to come up with one - I will correct)
I am working on an angular application where I have some menues and a search result list. I also have a document view area.
You can sort of say that the application behaves like an e-mail application.
I have a few controllers:
DateCtrl: creates a list of dates so the users can choose which dates they want to see posts from.
SourceCtrl: Creates a list of sources so the user can choose from which sources he/she wants to see posts from.
ListCtrl: The controller populating the list. The data comes from an elastic search index. The list is updated every 10-30 seconds (trying to find the best interval) by using the $interval service.
What I have tried
Sources: I have tried to make this a filter, but a user clicks two checkboxes the list is not sorted by date, but on which checkbox the user clicked first.
If it is possible to make this work as a filter, I'd rather continue doing that.
The current code is like this, it does not do what I want:
.filter("bureauFilter", function(filterService) {
return function(input) {
var selectedFilter = filterService.getFilters();
if (selectedFilter.length === 0) {
return input;
}
var out = [];
if (selectedFilter) {
for (var f = 0; f < selectedFilter.length; f++) {
for (var i = 0; i < input.length; i++) {
var myDate = input[i]._source.versioncreated;
var changedDate = dateFromString(myDate);
input[i]._source.sort = new Date(changedDate).getTime();
if (input[i]._source.copyrightholder === selectedFilter[f]) {
out.push(input[i]);
}
}
}
// return out;
// we need to sort the out array
var returnArray = out.sort(function(a,b) {
return new Date(b.versioncreated).getTime() - new Date(a.versioncreated).getTime();
});
return returnArray;
} else {
return input;
}
}
})
Date: I have found it in production that this cannot be used as a filter. The list of posts shows the latest 1000 posts, which is only a third of all posts arriving each day. So this has to be changed to a date-search.
I am trying something like this:
.service('elasticService', ['es', 'searchService', function (es, searchService) {
var esSearch = function (searchService) {
if (searchService.field === "versioncreated") {
// doing some code
} else {
// doing some other type of search
}
and a search service:
.service('searchService', function () {
var selectedField = "";
var selectedValue = "";
var setFieldAndValue = function (field, value) {
selectedField = field;
selectedValue = value;
};
var getFieldAndValue = function () {
return {
"field": selectedField,
"value": selectedValue
}
};
return {
setFieldAndValue: setFieldAndValue,
getFieldAndValue: getFieldAndValue
};
})
What I want to achieve is this:
When no dates or sources are clicked the whole list shall be shown.
When Source or Date are clicked it shall get the posts based on these selections.
I cannot use filter on Date as the application receives some 3000 posts a day and so I have to query elastic search to get the posts for the selected date.
Up until now I have put the elastic-search in the listController, but I am now refactoring so the es-search happens in a service. This so the listController will receive the correct post based on the selections the user has done.
Question is: What is the best pattern or method to use when trying to achieve this?
Where your data is coming from is pretty irrelevant, it's for you to do the hook up with your data source.
With regards to how to render a list:
The view would be:
<div ng-controller='MyController as myCtrl'>
<form>
<input name='searchText' ng-model='myCtrl.searchText'>
</form>
<ul>
<li ng-repeat='item in myCtrl.list | filter:myCtrl.searchText' ng-bind='item'></li>
</ul>
<button ng-click='myCtrl.doSomethingOnClick()'>
</div>
controller would be:
myApp.controller('MyController', ['ElasticSearchService',function(ElasticSearchService) {
var self = this;
self.searchText = '';
ElasticSearchService.getInitialList().then(function(list) {
self.list = list;
});
self.doSomethingOnClick = function() {
ElasticSearchService.updateList(self.searchText).then(function(list) {
self.list = list;
});
}
}]);
service would be:
myApp.service('ElasticSearchService', ['$q', function($q) {
var obj = {};
obj.getInitialList = function() {
var defer = $q.defer();
// do some elastic search stuff here
// on success
defer.resolve(esdata);
// on failure
defer.reject();
return defer.promise();
};
obj.updateList = function(param) {
var defer = $q.defer();
// do some elastic search stuff here
// on success
defer.resolve(esdata);
// on failure
defer.reject();
return defer.promise();
};
return obj;
}]);
This code has NOT been tested but gives you an outline of how you should approach this. $q is used because promises allow things to be dealt with asynchronously.
I'm searching through clients invoices
These invoices are stored within the client json.
so...
clients: {
... : {
invoices: {
},
},
}
I'm doing this by this:
var ref = new Firebase(fbUrl+'/clients/'+client+'/invoices/');
ref.on("value", function(snapshot) {
var list = snapshot.val();
angular.forEach(list, function(item) {
if(item.settings.number == id)
{
console.log(item.id());
invoice.details = item;
}
})
});
Inside the "if" how do I get the unique id auto generated by Firebase? In your html your able to do $id typically.
Once you call snapshot.val(), you're just dealing with a Javascript object. See the documentation for angular.forEach. You just need to specify a second argument to the function.
angular.forEach(list, function(item, key) {
...
});
Morning,
We are trying to implement this add row Plunkr, it seems to work however our input data seems to repeat. Does anyone know of a solution to add a unique id to preview duplicated fields ?
Here is our current Plunkr and LIVE example.
$scope.addRow = function(){
var row = {};
$scope.productdata.push(row);
};
$scope.removeRow = function(index){
$scope.productdata.splice(index, 1);
};
$scope.formData you have is not an array, but just one object. All your rows are bound to that object and hence all of them reference the same data.
The reason you get a new row added is because your ng-repeat is bound to $scope.productData and you add extra record in it. You should bind your form elements to the properties in the row object that you create
a simple example is :
In your template
<div ng-repeat="product in products">
<input type="text" ng-model="product.title">
</div>
In your controller
$scope.addProduct = function(){
var product = {};
$scope.productData.add(product);
}
You'd then always only work with the productData array and bind your model to them.
Even in your backend calls, you'd use productData instead of your formData.
Hope this helps.
U can use a filter : This will return Unique rows only
app.filter('unique', function () {
return function (items, filterOn) {
if (filterOn === false) {
return items;
}
if ((filterOn || angular.isUndefined(filterOn)) && angular.isArray(items)) {
var hashCheck = {}, newItems = [];
var extractValueToCompare = function (item) {
if (angular.isObject(item) && angular.isString(filterOn)) {
return item[filterOn];
} else {
return item;
}
};
angular.forEach(items, function (item) {
var valueToCheck, isDuplicate = false;
for (var i = 0; i < newItems.length; i++) {
if (angular.equals(extractValueToCompare(newItems[i]), extractValueToCompare(item))) {
isDuplicate = true;
break;
}
}
if (!isDuplicate) {
newItems.push(item);
}
});
items = newItems;
}
return items;
};
});
I think the reason why this is happening is that the addRow() function is just pushing an empty son object into the $scope.productdata array, whereas all input fields are bound to $scope.formData[product.WarrantyTestDescription]. I think you mean to bind the input fields to the properties of the product object.