How to select value inside an object - angularjs

I'm trying to store 1 or more values that are inside an array into a scope. This is the result of my JSONP service,
angular.callbacks._7({
"id":157336,"results":[
{"id":"53db3c790e0a26189a000d09","iso_639_1":"en","key":"ePbKGoIGAXY","name":"Trailer 3","site":"YouTube","size":1080,"type":"Trailer"},
{"id":"550df44b9251413554004d43","iso_639_1":"en","key":"KlyknsTJk0w","name":"Own it today","site":"YouTube","size":720,"type":"Trailer"},
{"id":"533ec6fcc3a3685448009ccc","iso_639_1":"en","key":"nyc6RJEEe0U","name":"Teaser","site":"YouTube","size":720,"type":"Trailer"},
{"id":"5376ab510e0a26141c0005a8","iso_639_1":"en","key":"zSWdZVtXT7E","name":"Trailer","site":"YouTube","size":720,"type":"Trailer"},
{"id":"545da247c3a3685362005187","iso_639_1":"en","key":"Lm8p5rlrSkY","name":"Trailer 2","site":"YouTube","size":1080,"type":"Trailer"}
]
})
And I'm trying to store all the key values inside a scope called $scope.youtubeTrailer
But if I do it like this,
$scope.youtubeTrailer = response;
console.log ($scope.youtubeTrailer)
The scope consists of an object (the movie) and inside that object is an array with the 5 id's. So what would be the correct selector for something like this?
If I search like this,
console.log ($scope.youtubeTrailer.key)
I get an 'undefined´
* EDIT *
I've tried to solution below,
movieAdd.trailer(movie.id)
.then(function(response){
$scope.youtubeTrailer =[];
console.log ($scope.youtubeTrailer)
angular.forEach(response.results, function(item){
console.log ('Hello world')
if (item.hasOwnProperty('key')) {
$scope.youtubeTrailer.push(item.key);
}
});
The console.log ($scope.youtubeTrailer) shows that the scope is empty. And the forEach function doesnt fire because the Hello log doesn't get shown in the console. If I change $scope.youtubeTrailer =[]; into $scope.youtubeTrailer = response; I do have the object in the scope but still the forEach doesn't fire.
* EDIT 2 *
By changinge response.results into response the forEach does fire.
* EDIT 3 *
I've got it somewhat working. I was getting the array in the scope, but when I saved the scope value in the create function it showed as null in the database. That's because I was trying to save an array. Using javascripts join I converted the array to a string which can be saved.
movieAdd.trailer(movie.id)
.then(function(response){
$scope.youtubeTrailer = [];
angular.forEach(response, function(item){
if (item.hasOwnProperty('key')) {
$scope.youtubeTrailer.push(item.key);
var youtubeArray = $scope.youtubeTrailer
var youtubeString = youtubeArray.join();

The code below basically is looping through the response.results array, which contains 5 objects. Each oject is assigned to the variable item. Check item has property of key, if true, add the value of item.key to $scope.youtubeTrailer.
$scope.youtubeTrailer =[];
angular.forEach(response.results, function(item) {
if (item.hasOwnProperty('key')) {
$scope.youtubeTrailer.push(item.key);
}
});
Here is the link for Angular ForEach.

$scope.youtubeTrailer isn't just an object, it contains an array and its inside that array that the key field is. So, you're going to need to access the five interior items with an array access. e.g. $scope.youtubeTrailer.results[0].key

Related

how to push scope value inside the array in array in angularjs

hi all i am using angularjs i am trying to do push the scope variable to another scope array i paste my code also my need my scope array look like this here i have get the value from two scope and push into one scope variable it's work fine my need is i want push the $scope.ViewGetMaterialStreams value inside the Materialselection id when i expand the id i need one array called name how to declare help how to do this
$scope.Materialselection ={id: [?i need the Namecolumn here in array]};
for(var i=0 ;i<$scope.BFMaterial.length;i++) {
$scope.Materialselection.stream.push($scope.BFMaterial[i]);
$scope.Materialselection.stream.push($scope.ViewGetMaterialStreams[i].name);
}
here i exapnd 0 i get output id:121 look like this now my need is when i expand 0 i need to show expand 0 i want show id :12121,name:dfdf
try this
$scope.Materialselection.stream =[];
$scope.BFMaterial.forEach(function(item, index) {
var obj = {};
obj.id = item.id;
obj.name = $scope. ViewGetMaterialStreams[index].name;
$scope.Materialselectio.stream.push(obj);
});
You can do it in following way:
$scope.Materialselection =[];
angular.forEach($scope.BFMaterial,function(item, index) {
var obj = {
id: item.id,
name: $scope.ViewGetMaterialStreams[i].name
};
$scope.Materialselection.push(obj);
});

How to check if value already exists?

I have a small app that users can use to search for a movie, and then add it to their watchlist. Currently it is possible to add 1 movie multple times for the same user. Which ofcourse isn't expected behaviour.
My solution would be to find the unique id of the movie that's being added and crosscheck that with my movies_users data. If the movie_id value exists, do this, else do this.
At the moment I do have the unique movie id of the movie that's being added,
$scope.movieListID = response;
console.log ($scope.movieListID.id)
Which gets ouputted like a string, like so,
314365
And I got the movie records from the current user,
$scope.moviesCheck = response.data;
console.log ($scope.moviesCheck)
Which looks like this,
[{"id":2,"title":"Black Panther", "movie_id":"284054"}]
So what would be a good way to check if the result from $scope.movieListID.id already exists in the $scope.moviesCheck data?
* update *
Trying a suggestion below does not give the expected result.
var exists = function (id) {
$scope.moviesCheck.forEach(function (movie) {
console.log (movie.movie_id)
console.log (id)
if (movie.movie_id === id)
console.log ('duplicate')
else
console.log ('not duplicate')
});
}
exists($scope.movieListID.id);
The console.log output from this is,
312221
312221
not duplicate
Which clearly are duplicate results.
You can add a function in your controller to check if the movie exists in the list
var exists = function (id) {
$scope.moviesCheck.forEach(function (movie) {
if (movie.id === id)
return true;
});
return false;
}
// and call it
exists($scope.movieListID.id); // true or false
I'm not 100% if this is a good way to do this, but for me it works and I think it's pretty low on performance,
movieService.loadMovies().then(function(response) {
$scope.moviesCheck = response.data;
var arr = $scope.moviesCheck
function myIndexOf(o) {
for (var i = 0; i < arr.length; i++) {
if (arr[i].movie_id == o.exisitingMovie_id) {
return i;
}
}
return -1;
}
var checkDuplicate = (myIndexOf({exisitingMovie_id:movie.id}));
if (checkDuplicate == -1) {
From your question I've understood that, based on the object exists using id in the array of object, you have to do different action.
You can use $filter for this. Inject the filter for your controller and assign it to the scope. So this will be available whenever you want in this controller.
$scope.cFilter('filter')($scope.movies, {movie_id:$scope.existingMovie.movie_id}, true);
$sope.movies - is the list of movies passed to the filter. You can
send any list based on your need.
{movie_id:$scope.existingMovie.movie_id} - This one is the object
which one we need to find. This can be based on your need. Since we
are searching movie_id, we need to send the object with property
and value. {movie_id:$scope.existingMovie.movie_id}, Here movie_id is
the property and followed by the value with the colon.
true: This indicates that, to search exact matched values. By default
this is false. If this is set to false, then if we want to search 54
in the movie id, this will returns the objects whichever contains 54
as part of the value.
app.controller('controller', ['$filter',function($filter){
$scope.cFilter= $filter;
$scope.Exists=function(){
$scope.movies=[{"id":2,"title":"Black Panther", "movie_id":"284054"},{"id":3,"title":"Black Panther", "movie_id":"32343"},{"id":4,"title":"Black Panther", "movie_id":"98863"}]
$scope.existingMovie={"id":3,"title":"Black Panther", "movie_id":"32343"};
var _obj=$scope.cFilter('filter')($scope.movies, {movie_id:$scope.existingMovie.movie_id}, true);
if(_obj && _obj[0])
{
Console.log('object exists')
}
else
{
Console.log('Object is not found')
}
}
}])
Many Thanks Jeeva Jsb. This got me on the right track, however I thought I would clarify with a practical example that seems to work as expected.
So I have a function called getData which get the AJAX array but we need to check if the record exist before added to scope (else we get duplicates)
if (d.data.length) {
for (var i = 0; i < d.data.length; i++) {
var doesExist = $filter('filter')($scope.notifications, {NotifId:d.data[i].NotifId}, true);
if (doesExist.length == 0){
$scope.notifications.push(d.data[i]);
}
}
}
This should look familier...
when we are iterating through the returned AJAX object we need to check the ID of the (in my case notificiation)
var doesExist = $filter('filter')($scope.notifications, {NotifId:d.data[i].NotifId}, true);
This line creates a new array by filtering the existing array in scope ($scope.notifications) and passing in the same value from you interation.
If the value exists the object will be copied to the new array called doesExist.
A simple check of length will determine if the record needs to be written.
I hope this helps someone.

Using Angular to append next set of results

I have data that i'm getting from an external API via jsonp.
I have requested the first 10 results. This comes back as an object.
I have new call with a button to fetch the next 10 results from it's cache but it just overwrites the first set of returned data.
How can I get Angular to append or push each subsequent data to the bottom?
$scope.getEanApi = function(){
devaFactory.searchRequest()
.then(function(data){
$scope.hotels = data.HotelListResponse.HotelList;
}).finally(function(){
});
return;
};
$scope.getEanApi();
$scope.moreResults = function(){
devaFactory.moreResults()
.then(function(data){
$scope.hotels = data.HotelListResponse.HotelList;
angular.extend($scope.hotels,$scope.hotels);
}).finally(function(){
});
return;
};
If it's an array then do as below:
$scope.data = $scope.data.concat(newData);
However it changes array reference with merged array so if you've used ng-repeat then it will redraw for whole array. If you're using any animation then you may want to redraw for newly elements only so for that append your new array data manually by iterating through as below.
for(var j=0;j<newData.length;j++) {
$scope.data.push(newData[j]);
}
If it's object then do
angular.extend($scope.data,newData);

Getting id undefined in angularJs service

I have followed tutorial : http://viralpatel.net/blogs/angularjs-service-factory-tutorial/
But, when I try to save a new record, I am getting newcontact.id as undefined and unable to save new record.
What would be the problem?
you need to add this piece of code
var original = {itemCategory:null,itemName:null,
itemPrice:null,purchaseDate:null,applianceType:null,
insStatus:null,id:null};
$scope.newitem = angular.copy(original);
and edit the saveItem function as this
$scope.saveItem = function () {
alert("add new");
DataStoreService.save($scope.newitem);
$scope.newitem = angular.copy(original);
}
here is the working Plunker
please not that i remove the <script src="angular-dropdowns.min.js"></script> and the ngDropdowns dependency of var app = angular.module('app', ['ngDropdowns']);, to get rid some console errors which are not causing this issue.
The cause of the problem
the problem of getting id undefined is, you didn't define a variable called $scope.newitem with in the controller, instead you straightly use newitem with in the HTML, then your controller dosen't know about this newitem until you change any input.
if you change any input say itemName then the controller knows there is no $scope variable called newitem, then the angular will create the newitem object and a itemName property inside that newitem object , after changing itemName input say u change the itemPrice then the controller search for the newitem object and put the property itemPrice in to the object, ok now you have two properties inside the newitem, like wise the process goes with your inputs, but the id field is a hidden field and your not going to change the value inside html, that means in your newitem object you don't have id property. that`s why its getting undefined.
to scarify,
add a line as the first statement as console.log($scope.newitem); in the $scope.saveItem function and check the $scope.newitem object, here is the Plunker to test it
press save without changing any input
this red color can not read id of undefined error is because we pass the $scope.newitem to the service which is undefined, so the script can not get the id field of item which is undefined in the line of alert("save"+ item.id);). item is undefined
change only the itemName and press save
here you will get a alert saying saveundefined this is because of the alert in line alert("save"+ item.id);). In this line item which is not undefined but the id property of the object is not set , so item.id is undefined, that's why its alert saveundefined. item is defined but item.id is undefined
Solution
create a object to hold default values of all the newitem properties
var original = {itemCategory:null,itemName:null,
itemPrice:null,purchaseDate:null,applianceType:null, insStatus:null,id:null};
get a deep copy of that object and assign it to newitem
$scope.newitem = angular.copy(original);
after saving the newitem reset the newitem object to default object we defined,
$scope.saveItem = function () {
alert("add new");
DataStoreService.save($scope.newitem);
$scope.newitem = angular.copy(original);
}

Returning values of a fetch

Please look at the code below. It's a Backbone/Parse code that uses some underscore features.
I'm trying to iterate over an Parse class to retrieve "firstName" attributes of all objects in that class.
I have 2 issues with it.
The first one, as indicated with the comment, is that it correctly retrieves the first names, but it duplicates them. So if there are 5 objects, it will retrieve 5 firstName * 5. There is an iteration problem here. This is shown with the console log.
Second problem, is that I try to push firstName values into an array, then return it, so I can use the values later in code using the testt variable. But checking the testt content with a console log sends a message instead of the firstname lists.
Do you see anyway how to fix this code ?
var DoopizCollection = Parse.Collection.extend({
model: Subscribers
}
);
var doopizlist = new DoopizCollection();
var testt;
testt = doopizlist.fetch({
success: function(doopizlist) {
var results = [];
doopizlist.each(function(object) {
results.push(doopizlist.pluck('firstName'));
console.log(doopizlist.pluck('firstName')); // logs 2 duplicate arrays
});
return results;
},
error: function(doopizlist, error) {
console.log("error"); // The collection could not be retrieved.
}
});
console.log(testt); // logs "a b.promise...." message instead of firstNames
The duplication issue is because you are looping over doopizlist twice, once with each and again with pluck. Pluck is just basically shorthand of the map method.
The second issue is, you are expecting testt is the resulting value, when actually it is an instance of jqXHR, which is something known as a promise. So you can use the then method to log the value of the result.
var DoopizCollection = Parse.Collection.extend({
model: Subscribers
}
);
var doopizlist = new DoopizCollection();
var testt;
testt = doopizlist.fetch({
success: function(results) {
return results.pluck('firstName');
},
error: function(results, error) {
console.log("error"); // The collection could not be retrieved.
}
});
testt.then(function(results) {
console.log(results);
});

Resources