AngularJS, get data from external source and push into array - javascript

I'm trying to call an external scrip that gets data from a database, so I can then populate a select dropdown. I've tried this so far, but I get a load of empty li elements. It is the right count of what there should be just nothing showing?
My controller
app.controller('agenciesController', function($scope, $http) {
var url = "/ajax/getAgencies.php";
$http.get(url).success( function(response) {
$scope.agencies = response;
$scope.agenciesArray = [];
angular.forEach(response, function(value, key){
$scope.agenciesArray.push(value);
})
console.log($scope.agenciesArray);
});
})
My HTML
<body ng-controller="Controller">
<div ng-controller="agenciesController">
<ul ng-repeat="agencyName in agencies">
<li>{{agenciesArray.agencyID}}</li>
</ul>
</div>
</body>
UPDATE -
This code is working but not returning only one response but all.
<div ng-controller="agenciesController">
<ul ng-repeat="agencyName in agenciesArray">
<li>{{agencyName}}</li>
</ul>
</div>

agenciesArray is an array. agenciesArray.agencyID will be undefined. that is why you are gettting empty li.
Do you intend to do this?
<ul ng-repeat="agency in agenciesArray">
<li>{{agency.agencyName}}</li>
</ul>

Try this
<ul ng-repeat="agencyName in agencies">
<li>{{agencyName.agencyID}}</li>
</ul>
Reason:Because agencyArray is nothing in the given context

Related

How to iterate through array as item is added in Angularjs?

I used ng-repeat to loop through array made in controller. The problem is, instead of showing each value in a new row, it shows all of the array values in every row, like below:
The html code looks like this:
<div ng-model="wrapper_div" id="wrapper">
<input type="button" value="Update Data"
ng-click="updateData()" />
<ul ng-repeat="x in data">
<li>{{data}}</li>
</ul>
</div>
And the script:
var answers = [];
function updateData(data) {
var scope = angular.element($("#wrapper")).scope();
scope.$apply(function(){
answers.push(data);
scope.data = answers;
});
}
The expected result should look like:
9
6
7
And NOT this:
9,6,7
9,6,7
9,6,7
you are displaying data not x , data is an array , so complete array is displayed three time , instead display {{x}} try
<ul ng-repeat = "x in data"><li>{{x}}</li></ul>
You probably need to move your ng-repeat to the li tag, not the ul. and in the expression, use x and not data, which is why you are getting the whole array printed every time. so your html should look something like :
<div ng-model = "wrapper_div" id="wrapper">
<input type="button" value="Update Data" ng-click="updateData()"/>
<ul>
<li ng-repeat = "x in data">{{x}}</li>
</ul>
</div>

how to print array object array in html using angualrjs

I am trying to take data from a movie API (TMDB API) and want to display the details of the movie in my html view page.
I got the response from the API but i cannot figure out the way to handle the response that is in array of an object array.
This is my response
{
"page":1,
"total_results":1,
"total_pages":1,
"results":
[{
"vote_count":779,
"id":20453,
"video":false,
"vote_average":7.7,
"title":"3 Idiots",
"popularity":1.963226,
"poster_path":"\/wbE5SRTZFtQxgj2nIo4HJpQDk0k.jpg",
"original_language":"hi",
"original_title":"3 Idiots",
"genre_ids":[18,35,10749],
"backdrop_path":"\/6LnwpadKFRrqam7IfBAi3lNTz6Y.jpg",
"adult":false,
"overview":"In the tradition of “Ferris Bueller’s Day Off” comes this
refreshing comedy about a rebellious prankster with a crafty mind anda
heart of gold. Rascal. Joker. Dreamer. Genius... You've never met a
college student quite like \"Rancho.\" From the moment he arrives at
India's most prestigious university, Rancho's outlandish schemes turn
the campus upside down—along with the lives of his two newfound best
friends. Together, they make life miserable for \"Virus,\" the
school’s uptight and heartless dean. But when Rancho catches the eye
of the dean's sexy daughter, Virus sets his sights on flunking out the
\"3 idiots\" once and for all.",
"release_date":"2009-12-23"
}]
}
I want to display overview and other details that is in results in my html page using angularjs but i cannot figure out how to do that?
This is my js and html code snippet. Where i try this with another API but now it got private so i have to change the API.
function getItems(){
$http({method:'GET',url:"https://api.themoviedb.org/3/search/movie?api_key=9a1750d469929884b1c959126ec22c83&query=" + $scope.search})
.then(function (response) {
// body...
$scope.movies = response.data.results;
console.log(response.data.results);
});
<div class="movie-details col-sm-8" >
<ul class="details">
<li><img ng-src="{{movies.Poster=='N/A' && 'http://placehold.it/150x220&text=N/A' || movies.poster_path}}" class="movie-poster thumbnail"><a class="movie-title" href="http://www.imdb.com/title/{{movies.imdbID}}" target="_blank">{{movies.original_title}}</a>, {{movies.Year}} <span class="reviews">Reviews | Add your own review</span></li>
<li><span>Released On: </span>{{movies.results}}</li>
<li><span>Runtime: </span>{{movies.Runtime}}</li>
<li><span>Genre: </span>{{movies.Genre}}</li>
<li><span>Director: </span>{{movies.Director}}</li>
<li><span>Writers: </span>{{movies.Writer}}</li>
<li><span>Actors: </span>{{movies.Actors}}</li>
<li>{{movies.overview}}</li>
<li><span>Language: </span>{{movies.Language}}</li>
<li><span>Country: </span>{{movies.Country}}</li>
<li><span>Awards: </span>{{movies.Awards}}</li>
<li><span>IMDB Ratings: </span>{{movies.imdbRating}}</li>
</ul>
<br>
<div>
<a class="links" href="https://www.youtube.com/results?search_query={{movies.original_title}}" target="_blank">Watch Trailers!</a>
|<a class="links" href="https://subscene.com/subtitles/title?q={{movies.Title}}&l=" target="_blank">Get Subtitles!</a>
|<a class="links" href="http://www.amazon.in/s/ref=nb_sb_noss_1?url=search-alias%3Ddvd&field-keywords={{movies.Title}}" target="_blank">Buy Online!</a>
</div>
</div>
You have to use ng-repeat in order to show data in your html, further correct the property names that you bind on html. (for example: results to release_date)
(see this screenshot of console log data)
Sample DEMO :
var myApp = angular.module('myApp', []);
myApp.controller('ExampleController', ExampleController);
function ExampleController($scope, $http) {
function callapi() {
$http({
method: 'GET',
url: 'https://api.themoviedb.org/3/search/movie?api_key=9a1750d469929884b1c959126ec22c83&query=3%20idiot'
}).then(function(response) {
console.log(response.data.results[0]);
$scope.moviesData= response.data.results;
})
}
callapi();
}
<script src="https://code.angularjs.org/1.5.2/angular.js"></script>
<div ng-app="myApp" ng-controller="ExampleController">
<ul ng-repeat="movies in moviesData">
<li><span>Released On: </span>{{movies.release_date}}</li>
<li><span>Runtime: </span>{{movies.Runtime}}</li>
<li><span>Genre: </span>{{movies.Genre}}</li>
<li><span>Director: </span>{{movies.Director}}</li>
<li><span>Writers: </span>{{movies.Writer}}</li>
<li><span>Actors: </span>{{movies.Actors}}</li>
<li>{{movies.overview}}</li>
<li><span>Language: </span>{{movies.original_language}}</li>
<li><span>Country: </span>{{movies.Country}}</li>
<li><span>Awards: </span>{{movies.Awards}}</li>
<li><span>IMDB Ratings: </span>{{movies.imdbRating}}</li>
<hr>
</ul>
</div>
It looks like you are not using the results exactly as you should be. For instance you have movies.results but you already set $scope.movies to your return results properties.
Make sure that you are using the properties within the results property that you set movies to.
For example you could access the overview by calling {{movies.overview}} in your HTML

How to call function dynamically in JQuery

I've set of html codes, I want to have a function for each set where I can pull some data or do some activities, so basically I need to be calling function according to the html codes present in DOM, suppose I've header section I want to collect menu items and I've sliders where I want to collect slider information, So I need to call header function to do the activity accordingly and slider function to do the activity, I went across some info about eval() but I guess it has lot of demerits and is being obsolete. Please suggest me how can I achieve it.
HTML Code:
Header
<div class="header" data-nitsid="1">
<div class="branding">
<h1 class="logo">
<img src="images/logo#2x.png" alt="" width="25" height="26">NitsOnline
</h1>
</div>
<nav id="nav">
<ul class="header-top-nav">
<li class="has-children">
Home
</li>
</ul>
</nav>
</div>
Slider
<div id="slideshow" data-nitsid="2">
<div class="revolution-slider">
<ul> <!-- SLIDE -->
<!-- Slide1 -->
<li data-transition="zoomin" data-slotamount="7" data-masterspeed="1500">
<!-- MAIN IMAGE -->
<img src="http://placehold.it/1920x1200" alt="">
</li>
</ul>
</div>
</div>
Now I want to collect data from both elements and pass the data to my views of laravel framework where it will generate a popup for each section for editing purpose.
$('.page-content-wrapper').find('[data-nitsid]').each(function() {
// getting data to call function
var nits = $(this).data("nitsid");
// calling function
design.nits();
}
var design = {};
design.1 = function() {
// do ajax request to views of header
}
design.2 = function() {
// do ajax request to views of slider
}
You canot use literal number as a property name. If you want to call property 1 of object design use design[1] instead. Also, you cannot assing property to non-initialized variable, you must use var design = {}; to make it object. If your property of design object is stored in nits variable, then call it as design[nits]();. Also, next time don't forget to test your code before posting it here. You've forget ) after your first function.
$('.page-content-wrapper').find('[data-nitsid]').each(function() {
// getting data to call function
var nits = $(this).data("nitsid");
// calling function
design[nits]();
});
var design = {};
design[1] = function() {
// do ajax request to views of header
};
design[2] = function() {
// do ajax request to views of slider
};
You want to use design[nits]();.
This will get the property nits of design and execute it with ().
But there is another problem. Your design will be declared after the each loop, so it is not available inside. You have to place it before.
$(function() {
var design = {};
design.funcOne = function() {
alert("funcOne called");
}
design.funcTwo = function() {
alert("funcTwo called");
}
$('div[data-nitsid]').each(function() {
var nits = $(this).data("nitsid");
design[nits]();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-nitsid="funcOne">
I will call 'funcOne'!
</div>
<div data-nitsid="funcTwo">
I will call 'funcTwo'!
</div>

Angular - populate list with AJAX

I am working on a web app, and I want to show data in a list, by category. I am getting back AJAX data that has a title, and a category. The code to get that is like this:
angular.module('getImageData', ['ngResource'])
.factory('images', function ($resource)
{
return $resource('/ImageData/GetImages', {}, {
query: { method: 'GET', isArray: true }
});
});
and then like this:
$scope.imageData = images.query(function (response)
{
// This has become superfluous
return response;
});
The AJAX call us occurring and I can see my data in Chrome.
Then here is my HTML:
<ul>
<li data-ng-repeat="image in imagedata">
{{image.Title}}
</li>
</ul>
I intend to do this:
<ul>
<li data-ng-repeat="image in imagedata | filter : {TypeFilter : 'a' }">
{{image.Title}}
</li>
</ul>
but for now I'm keeping it simple.
The list is never rendered. This is the HTML I see in chrome:
<ul>
<!-- ngRepeat: image in imagedata -->
</ul>
I am assuming this means it ran before the data came back. How do I make it wait ?
Thanks.
You have a spelling mistake in image in imagedata. It should be image in imageData
You also do not need to write callback function for query
$scope.imageData = images.query();
try changing this:
$scope.imageData = images.query(function (response)
{
// This has become superfluous
return response;
});
to this:
$scope.imageData = images.query(function (response)
{
$scope.imageData = response;
});

Angular factory filter - Can't get data passed to the filter

I'm looking through the Angular docs and I can't better documented stuff.
My problem is as follows:
I have a filter:
.filter('filteringService', function () {
return function (photos, categsList) {
if (photos !== undefined) {
var filteredPosts = [];
console.log('Categories or Selected Categories:');
console.log(categsList);
//DEVEL Only, assign a SEARCH value, can't pass the data from the list now.
categsList = 'people';
if (categsList === undefined) {
for(i=0; i < photos.length; i++) {
filteredPosts.push(photos[i]);
}
} else {
console.log('Trying to push a category slug to search for.');
//TASK: Convert in multiple possible selections.
filteredPosts = [];
}
console.log('Filter returns ' + filteredPosts.length + ' posts');
return filteredPosts;
}
};
});
And I have the template
<div class="photos">
<div class="filters">
<ul>
<li><a>ALL</a></li>
<li ng-repeat="category in categsList">
<a ng-checked="category[0]" ng-model="category[0]">{{ category[1] }}</a>
</li>
</ul>
</div>
<ul class="photos-list">
<li ng-repeat="photo in photos|filteringService:category">
<h1>{{ photo.title }} click LINK</h1>
<ul class="categories">
<li ng-repeat="category in photo.categories">
{{ category.title }}
</li>
</ul>
</li>
</ul>
</div>
There's a huge object with posts called photos and then there's a category list called categsList.
The photos object has the items from the categs list in it. I WANT to be able to filter with the CLICKED element through that list, and maybe multiple filter, but first to pass on the actual filter value to the filter service, I can't seem to do that.
How should I do that?
Apparently I managed to pass the filter value, in a dirty way (I GUESS), like this
<a ng-bind="category.slug" ng-click="returnFilter(category.slug);" ng-model="category.slug">{{ category.title }}</a>
it goes here
$scope.returnFilter = function(theSlug) {
$scope.filterBy = theSlug;
};
and it comes out here
<li ng-repeat="photo in photos|filteringService:filterBy">
It's working, but Is this correct?
EDIT: Also with this way in mind, I could pass an array as theSlug so I can do multiple filtering, and when clicking two times on the same item it would get it out of the array. hmmm
EDIT 2:
Let's say the resulting array is under 15 items, could do I run some action in the controller knowing this?
Actually the other way around, could I query from the controller the resulting array that the filter outputs?
I can't $watch the first array, I guess the filter creates a new array and puts those results in page. How could I watch the resulting array for changes and do stuff in the controller?

Categories