AngularJS ng-repeat: push object to array - angularjs

I have an object for selectedProduct. I now want to create an array of these selectedProduct objects so I can build a list using ng-repeat. I;ve set the scope to an empty array but what is the angular way to push these so I can access them via ng-repeat, i.e. product in products.
$scope.products = [];
$scope.getProduct = function() {
ProductService.getProduct($scope.eanInput.ean)
.then(function(product) {
$scope.selectedProduct = product;
$scope.selectedProduct.ean = $scope.eanInput.ean;
$scope.selectedProduct.qtyInput = 1;
$scope.focusOn = 'qty';
$scope.eanInput.productFound = true;
})
.catch(function() {
$scope.eanInput.productFound = false;
});
};

To my knowledge there is no angular way of pushing an object into an array, you can just use the default javascript way:
$scope.products.push(product);

I would just push them to the array to be honest :
$scope.products = [];
$scope.getProduct = function() {
ProductService.getProduct($scope.eanInput.ean)
.then(function(product) {
$scope.selectedProduct = product;
$scope.selectedProduct.ean = $scope.eanInput.ean;
$scope.selectedProduct.qtyInput = 1;
$scope.focusOn = 'qty';
$scope.products.push(product)
$scope.eanInput.productFound = true;
})
.catch(function() {
$scope.eanInput.productFound = false;
});
};
then in html you can do :
<div ng-controller="YourCtrl">
<h1 ng-repeat="product in products">
{{product.ean}}
</h1>
</div>

Related

Showing dynamic content inside ngRepeat

Struggling to show dynamic content inside a ngRepeat. When it comes time to show my promise content, I'm getting an empty object {}:
<div ng-controller="DemoCtrl">
<div class="sidebar" ng-repeat="row in rows">
<div class="row">
<input type="checkbox">
<div class="name">{{row.name}}</div>
<div class="title">{{map[$index]}}</div>
</div>
</div>
</div>
and the controller:
function DemoCtrl($scope, $http, $q) {
const rows = function() {
const rows = [];
for (let i = 0; i < 12; i++) {
rows.push({
id: `demo-${i}`,
name: `Demo ${i}`
});
}
return rows;
};
$scope.rows = rows();
$scope.map = [];
// $scope.$watch($scope.map, function (oldValue, newValue) {
// console.log(oldValue, newValue);
// });
function _data() {
// const promises = [];
for (let i = 0; i < $scope.rows.length; i++) {
var defer = $q.defer();
$http.get(`https://jsonplaceholder.typicode.com/posts/${i + 1}`).then(function(post) {
defer.resolve(`${post.data.title.substring(0, 10)}...`);
});
$scope.map.push(defer.promise);
// promises.push(defer.promise);
}
// return $q.all(promises);
return $q.all($scope.map);
}
function _init() {
_data().then(function(data) {
$scope.map = data; // why aren't we getting here?
});
};
_init();
}
Plunker here: https://plnkr.co/edit/2BMfIU97Moisir7BBPNc
I've tinkered with some other ideas such as trying to add a $watch on the $scope object after the value changes, but I'm not convinced this will help in any way. Some lingering questions I have:
From what I understand, you can use a promise inside a template so how/why does this change inside a ngRepeat?
Why isn't my callback for $q.all getting called?
If this is not the right approach, what is?
In Angular you will almost never need to use $q.
You can simply fill an array of posts titles after each $http.get
function DemoCtrl($scope, $http) {
const rows = function () {
const rows = [];
for (let i = 0; i < 12; i++) {
rows.push({
id: `demo-${i}`,
name: `Demo ${i}`
});
}
return rows;
};
$scope.rows = rows();
$scope.map = [];
function _init() {
for (let i = 0; i < $scope.rows.length; i++) {
$http.get(`https://jsonplaceholder.typicode.com/posts/${i + 1}`).then(function (post) {
$scope.map.push(post.data.title);
});
}
}
_init();
}
https://plnkr.co/edit/zOF4KNtAIFqoCOfinaMO?p=preview

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

how to add an object to list an array in angularjs

I am trying to add an object to the existing list. here is my code.
In controller:
$scope.itemList = [];
$scope.itemList = function () {
return itemService.getItemList();
};
getItemList read from a jason file locally not from service. now I am trying to add new object to this list.
here is my view:
<div>
<img src="/icon1.png" ng-click="sendNewItem()">
<input type="text" ng-model="itemtosend.itemName"/>
<input type="text" ng-model="itemtosend.itemNo"/>
</div>
In controller:
$scope.sendNewItem = function(){
var newItem = new function(){
this.itemName = $scope.itemtosend.itemName,
this.itenNo = $scope.itemtosend.itemNo,
}
$scope.itemList = $scope.itemList.push(newItem)
}
but Iam getting push is not a function. how to add the new object to the existing itemList?
You have many problems in your code :
//You define itemList as an Array (so you can push() in it)
$scope.itemList = [];
//But you redefine it as a function (you cannot push() to a function, ofc..
$scope.itemList = function () {
return itemService.getItemList();
};
then :
$scope.sendNewItem = function(){
//you say newItem is a function, but I guess what you want is an object
var newItem = new function(){
this.itemName = $scope.itemtosend.itemName,
this.itenNo = $scope.itemtosend.itemNo,
}
//$scope.itemList.push(newItem) is enough, no need for list = list.push("b")
$scope.itemList = $scope.itemList.push(newItem)
}
What you should have is :
In controller:
$scope.itemList = [];
$scope.sendNewItem = function(){
var newItem = {
itemName : $scope.itemtosend.itemName,
itenNo : $scope.itemtosend.itemNo
};
$scope.itemList.push(newItem)
}
Please find bellow a code snippet :
var app = angular.module("App", []);
app.controller("Ctrl", function($scope) {
$scope.itemList = [];
$scope.sendNewItem = function() {
var newItem = {
name: $scope.itemtosend.itemName,
no: $scope.itemtosend.itemNo
};
$scope.itemList.push(newItem)
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="App" ng-controller="Ctrl">
<label>Name :</label><input type="text" ng-model="itemtosend.itemName" />
<label>No :</label><input type="text" ng-model="itemtosend.itemNo" />
<button ng-click="sendNewItem()">Add</button>
<h3>Item List :</h3>
<div ng-repeat="item in itemList">
name : {{item.name}}, num : {{item.no}}
</div>
</div>

Check for empty ng-repeat from controller

I'm a newbie in angularjs. And my template is something like this:
<div ng-repeat="item in values"></div>
<div ng-repeat="item1 in values1"></div>
And my controller:
$scope.openItems = function () {
$http.get('/api/openItems').success(function (data) {
$scope.values = data;
});
};
That is working fine. Now I want to show the items, only if it is empty.
I tried something like this:
$scope.openItems = function () {
$http.get('/api/openItems').success(function (data) {
if ($scope.values.length == 0) {
$scope.values = data;
} else {
$scope.values1 = data;
}
});
};
Any idea how to check from the controller is a ng-repeat has data in it?
Thanks in advance
Make sure you are initializing the arrays at the top, then you can just do something like this :
//initialize vars
$scope.values = [];
$scope.values1 = [];
$scope.openItems = function () {
$http.get('/api/openItems').success(function (data) {
if ($scope.values.length === 0) {
//you may or may not want to clear the second array if you are toggling back and forth
$scope.values1 = [];
$scope.values = data;
} else {
//empty the first one so we make the hide/show logic simple
$scope.values = [];
$scope.values1 = data;
}
});
};
then your html just looks like
<div ng-show="values.length" ng-repeat="item in values"></div>
<div ng-show="values1.length" ng-repeat="item1 in values1"></div>
Here is a quick proof of concept - http://jsfiddle.net/Lzgts/573/
You can also swap the ng-show with ng-if, if you want the divs to actually be taken off the DOM.
Depending on how your array is initialized (which we're not seeing) it might not ever have length==0 (for example I think it could be undefined, etc.) you could try:
if ($scope.values.length != 0) {
$scope.values1 = data;
} else {
$scope.values = data;
}

Get a list of contacts using cordova?

Sorry for my bad English.
How to get a list of contacts by using the Cordova angularjs?
Thanks in advance. Kind regards.
I don't know how your cordova-app is built up and but you could do it this way( take into consideration that I've not tested this):
Code:
First request contacts of your device by using the condact-plugin of cordova:
(same link as provided earlier: http://docs.phonegap.com/en/edge/cordova_contacts_contacts.md.html)
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
// when using the plugin:
// you can put it within your angularjs-controllers
// where it will be executed and onSuccess-callback is called.
var options = new ContactFindOptions();
options.filter = "";
options.multiple=true;
var fields = ["displayName", "name"];
navigator.contacts.find(fields, onSuccess, onError, options);
}
// within this function you have to assign contacts to a model
function onSuccess(contacts) {
$scope.contacts = contacts;
}
function onError(contactError) {
alert('onError!');
}
HTML:
Iterate over each contact-object of your contacts-collection assigned within onSuccess-function:
<div ng-repeat="contact in contacts">{{contact.name.formatted}}</div>
Tutorial: http://www.quora.com/What-is-the-way-to-get-all-contacts-using-PhoneGap-on-Android
Putting the plugin into a angularjs-controller could look like this:
angular.module('aModule', [])
.controller('contactCtrl', ['$scope', function($scope) {
var options = new ContactFindOptions();
options.multiple = true;
options.filter = "";
var fields = ["displayName", "name"];
navigator.contacts.find(fields,
function(contacts){
var arr = [];
for (var i = 0; i < contacts.length; i++)
{
arr.push({name: contacts[i].name.formatted})
}
$scope.contacts = arr;
},
function(error){ console.log(error); },
options
);
}])
HTML:
<div ng-app="aModule" ng-controller="contactCtrl">
<div ng-repeat="contact in contacts">{{contact.name}}</div>
</div>

Resources