AngularJS - how to pass id to api from nested ng-repeat - javascript

<div>
<ul ng-repeat="items in allcategories">
<p class="padding">{{ items.title }}</p>
<ion-slide-box show-pager="false" on-slide-changed="slideHasChanged($index)" class="padding">
<ion-slide ng-repeat="ite in allvodsforcategory">
<img ng-src="{{ ite.image }}">
</ion-slide>
</ion-slide-box>
</ul>
</div>
$http.get('http://api.com?user=' + $scope.apiusername + '&pass=' + $scope.apipassword + '&id=' . items.id).success(function(data) {
$scope.allvodsforcategory = data.videos;
});
$http.get('http://api.com?user=' + $scope.apiusername + '&pass=' + $scope.apipassword).success(function(data) {
$scope.allcategories = data.categories;
});
There is my code you can see the first ng-repeat on the ul item that is listing categories in side I want to list images no you can see the second ng-repeat on the ion-slide now I need to pass the items.id to the controller then put it into the url but I can not find a way to do that please help my all help is appreciated THANK YOU

If my understanding of your question is correct, I think that what you would have to do is create an isolate scope for your custom directive (ion-slide). This will allow you to pass the item id as an attribute. And it will be available to use in your controller. What I mean is:
...
.directive(ionSlide, function(...) {
return {
scope: {
itemId: '#',
},
.... // Other things
};
});
// In your html you would then have
...
<ion-slide item-id="{{item.id}}" ng-repeat="ite in allvodsforcategory">
<img ng-src="{{ ite.image }}">
</ion-slide>
...
// And in your controller,
...
.controller(function($scope, ...){
var id = $scope.itemId; // you have your id here.
$http.get('http://api.com?user=' + $scope.apiusername + '&pass=' + $scope.apipassword + '&id=' id).success(function(data) {
$scope.allvodsforcategory = data.videos;
});
});
Hope this helps.

Related

AngularJS append HTML in the ng-repeat element

Using AngularJS I need to append HTML to the elements of ng-repeat, using the selector: 'objectMapParent-' + post._id
<div ng-repeat="post in posts">
<div id="{{ 'objectMapParent-' + post._id }}">
<h5 style="color:blue; margin-top: 3px;">{{post.title}}</h5>
</div>
</div>
so I created a loop to loop through the elements of the posts array, where for each element I call the function: createElement
$scope.posts = [{
_id: "1",
title: "map of london"
}, {
_id: "2",
title: "map of brazil"
}, {
_id: "3",
title: "map of usa"
}];
$scope.posts.forEach(function(post) {
// console.log(post);
createElement("#objectMapParent-" + post._id, function() {
//create map here after append
});
});
This callback function gets a selector, elementParent, which we use to find the node in the DOM, and then apend the desired HTML
var createElement = function(elementParent, cb) {
var aux = elementParent;
var postId = aux.replace("#objectMapParent-", "");
var myElement = angular.element(document.querySelector(elementParent));
var html = "<div id='objectMap-" + postId + "'><div id='BasemapToggle-" + postId + "'></div></div>";
myElement.append(html);
cb();
};
But something does not work, as far as I'm concerned, the document.querySelector function can not find the selector.
It seems to me that when it tries to select, the node does not yet exist in the DOM.
I reproduced the code in the codepen, it might help.
How to Encapsulate jQuery code in a Custom Directive
Any jQuery code that manipulates the DOM should be encapsulated in a custom directive so that it is executed when the AngularJS framework ng-repeat directive instantiates the element.
<div ng-repeat="post in posts">
<div id="{{ 'objectMapParent-' + post._id }}">
<h5 style="color:blue; margin-top: 3px;">{{post.title}}</h5>
<my-element post="post"></my-element>
</div>
</div>
app.directive("myElement", function() {
return {
link: postLink,
};
function postLink(scope,elem,attrs) {
var post = scope.$eval(attrs.post);
var html = `
<div id="objectMap-${post._id}">
<div id="BasemapToggle-${post._id}">
</div>
</div>
`;
elem.append(html);
}
})
To use jQuery, simply ensure it is loaded before the angular.js file.
For more information, see
AngularJS Developer Guide - Creating Custom Directives
AngularJS angular.element API Reference

Understanding Angular Promises and API Calls -- Creating User Dashboard from API

I'm trying to create a simple dashboard that mimics the functionality shown here. I'd like to stick within an angular construct, but I've successfully confused myself into oblivion.I'm pretty new to Angular in general.
I am creating a simple dashboard based off of data from the Github API. I would like to reference the following data sources (where user is the value from the search bar and repo is the value clicked on from a repo list -- see linked example in 1st paragraph):
"https://api.github.com/users/" + user ----> returns general user info
"https://api.github.com/users/" + user + "/repos" ----> used for repo list
"https://api.github.com/repos/" + user + "/" + repo + "/events" ----> list of events per repo
Essentially, the app is supposed to work the following way:
The user types in the Github username in the search bar.
An API call is made to return the user information and repo list
(the first two urls I listed)
So far, I have this working.
THEN, based on the first selected repo in the returned dropdown list OR the selected value, the 3rd url will be called to return more data.
As far as I can tell, I need to incorporate Angular promises, since my 3rd Get request is not being recognized.
Can someone help me restructure my app.js code to ensure that:
- I have a set "repo" on page render (i.e. the 1st listed repo will be the default selected)
- The events api is called again after user interaction with the repo list
I was trying to follow something as explained here but I was a little confused at how to incorporate the username and selected repo. If someone could walk me through how I could add in those parameters (specified by the user) in my code, I would really appreciate it!
Here is my current code, for reference:
app.js
angular.module('myApp', ['ui.router'])
.controller('DashboardCtrl', function($scope, $state, $http){
// Set search model to 'mbostock' and the fetch function to contact the
// remote API and ensure the view is initialized. Load results when the search box changes.
$scope.$watch('search', function() {
initialFetch();
});
$scope.search = "mbostock";
// Make calls to the API for Users and Repo List
function initialFetch(){
$http.get("https://api.github.com/users/" + $scope.search)
.then(function(response){ $scope.userinfo = response.data; });
$http.get("https://api.github.com/users/" + $scope.search + "/repos")
.then(
function(response){ $scope.repolist = response.data;
// Create call for events listing based on repo choice
var repo = "";
// console.log(document.getElementById("repo1").value);
$(function() {
//For showing default url
MakeUrl();
// On repository selection, call events
$('#repo-select').on('change', function () {
if ($(this).val() == 0) {
repo = document.getElementById("repo1").value;
} else {
repo = $(this).val();
}
MakeUrl();
return false;
});
});
function MakeUrl() {
var finalUrl = "https://api.github.com/repos/" + $scope.search + "/" + repo + "/events";
console.log(finalUrl);
$http.get(finalUrl)
.then(function (response) { $scope.eventinfo = response.data; });
}
});
}
// Function select which ensures that the entire
// text is selected when the user clicks in the text input.
$scope.select = function(){
this.setSelectionRange(0, this.value.length);
}
})
index.html
<body>
<div class="container-fluid outerdiv" ng-app="myApp" ng-controller="DashboardCtrl">
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand"><b>Github User Information</b> <span class="span-style"></span></a>
</div>
<div class="input-group search-bar">
<input type="text" ng-model="search" ng-model-options="{ debounce: 800 }" onclick="select()" class="form-control" placeholder="Enter Github user login" autofocus />
<span class="input-group-addon bar-style"><i class="glyphicon glyphicon-search"></i></span>
</div>
</div>
</nav>
<noscript>
<div class="nojs">Javascript is either disabled or not supported in your browser. Please enable it or use a Javascript enabled browser.</div>
</noscript>
<div class="animated zoomInRight">
<div id="user-bio" class="col-sm-4 col-md-4">
<div>
<div class="avatar">
<img src="{{ userinfo.avatar_url }}" class="thumbnail animated flip movie-poster">
</div>
<span class="span-outer">
{{ userinfo.login }}
</span><br>{{ userinfo.name }}
<p><strong>Joined:</strong><br> {{ userinfo.created_at }}</p>
<p><strong>Last Updated:</strong><br> {{ userinfo.updated_at }}</p>
<p>{{ userinfo.bio }}</p>
<p class="outer-p">
<div class="inner-p">
<span class="label label-primary">Public Repos :</span> {{ userinfo.public_repos }}
</div>
<div class="inner-p">
<span class="label label-primary">Followers :</span> {{ userinfo.followers }}
</div>
<div class="inner-p">
<span class="label label-primary">Following :</span> {{ userinfo.following }}
</div>
</p>
</div>
<div ng-if="userinfo.message==='Not Found'">
No results found.
</div>
</div>
<div class="col-sm-8 col-md-8">
<h5><strong>Repositories:</strong></h5>
<select id="repo-select">
<option ng-repeat="repo in repolist" id="repo{{ $index + 1 }}" value="{{ repo.name }}" onchange="MakeUrl();">{{ repo.name }}</option>
</select>
<h5><strong>Events:</strong></h5>
<ul class="event-results" id="event-select" style="height:400px; overflow-y:auto;">
<li ng-repeat="event in eventinfo">
<a id="{{ $index + 1 }}" value="{{ event.type }}">{{ event.type }}
</a>, {{ event.created_at }} <!--ng-click="update(movie)"-->
</li>
</ul>
</div>
</div>
</div>
</body>
EDIT
Here is the error I'm seeing -- again, they seem to indicate I need to implement promises. Then again, I'm not sure why I can't specify a default selected repo.
Possibly unhandled rejection: {"data":{"message":"Not Found","documentation_url":"https://developer.github.com/v3"},"status":404,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"https://api.github.com/repos/mbostock//events","headers":{"Accept":"application/json, text/plain, /"}},"statusText":"Not Found"}
UPDATE AND EDIT
Via #mikwat 's suggestion, I tried using ng-model to bind the repo variable.
My new app.js file looks like this:
angular.module('myApp', ['ui.router'])
.controller('DashboardCtrl', function($scope, $state, $http, DataService){
// Set search model to 'mbostock' and the fetch function to contact the
// remote API and ensure the view is initialized. Load results when the search box changes.
$scope.$watch('search', function() {
initialFetch();
// .then(MakeUrl);
});
var user = $scope.search;
$scope.search = "mbostock";
$scope.repo = "array-source";
// Make calls to the API for Users and Repo List
function initialFetch(){
$http.get("https://api.github.com/users/" + $scope.search)
.then(function(response){ $scope.userinfo = response.data; });
$http.get("https://api.github.com/users/" + $scope.search + "/repos")
.then(
function(response){ $scope.repolist = response.data; },
$http.get("https://api.github.com/repos/" + $scope.search + "/" + $scope.repo + "/events")
.then(function (response) { $scope.eventinfo = response.data; })
);
}
// Function select which ensures that the entire
// text is selected when the user clicks in the text input.
$scope.select = function(){
this.setSelectionRange(0, this.value.length);
}
});
While this is getting the data to render, I cannot figure out how to dynamically assign the 1st repo list value as my default value (I tried document.getElementById("repo1").value but I got 'undefined') AND the function does not call the API again on dropdown change.
UPDATE 5/5/2017 -- Personal Solution
Big thanks to #mikwat for all the help. I ended up using a slightly different solution than he did below, but both work.
angular.module('myApp', [])
.controller('DashboardCtrl', function($scope, $http){
// Set search model to 'mbostock' and the fetch function to contact the
// remote API and ensure the view is initialized. Load results when the search box changes.
$scope.$watch('search', function() {
initialFetch();
// .then(MakeUrl);
});
// NOTE: watch for changes to repo
$scope.$watch('repo', function() {
$http.get("https://api.github.com/repos/" + $scope.search + "/" + $scope.repo + "/events")
.then(function (response) {
$scope.eventinfo = response.data;
});
});
var user = $scope.search;
$scope.search = "mbostock";
// Make calls to the API for Users and Repo List
function initialFetch(){
$http.get("https://api.github.com/events")
.then(function(response){ $scope.publicevents = response.data; console.log(response.data);})
.catch(function (err) {
console.log(err)
});
$http.get("https://api.github.com/users/" + $scope.search)
.then(function(response){ $scope.userinfo = response.data; })
.catch(function (err) {
console.log(err)
});
$http.get("https://api.github.com/users/" + $scope.search + "/repos")
.then(
function(response){
$scope.repolist = response.data;
// NOTE: select first repo
if ($scope.repolist && $scope.repolist.length > 0) {
var repo = $scope.repolist[0].name;
} else {
console.log("Something went wrong here!");
var repo = "undefined"
}
$scope.repo = repo;
return repo
}).then(function (repo) {
$http.get("https://api.github.com/repos/" + $scope.search + "/" + repo + "/events")
.then(function (response) { $scope.eventinfo = response.data; console.log(response.data);})
return repo;
}).then(function (repo) {
$http.get("https://api.github.com/repos/" + $scope.search + "/" + repo + "/languages")
.then(function (response) { $scope.languages = response.data; console.log(response.data);})
}).catch(function (err) {
console.log("Here!" + err);
});
};
// Function select which ensures that the entire
// text is selected when the user clicks in the text input.
$scope.select = function(){
this.setSelectionRange(0, this.value.length);
}
});
Here's a working solution. I removed some of the dependencies just to get it to work in this sandbox. I used NOTE: comments to help describe the important changes.
angular.module('myApp', [])
.controller('DashboardCtrl', function($scope, $http){
// Set search model to 'mbostock' and the fetch function to contact the
// remote API and ensure the view is initialized. Load results when the search box changes.
$scope.$watch('search', function() {
initialFetch();
// .then(MakeUrl);
});
// NOTE: watch for changes to repo
$scope.$watch('repo', function() {
$http.get("https://api.github.com/repos/" + $scope.search + "/" + $scope.repo + "/events")
.then(function (response) {
$scope.eventinfo = response.data;
});
// NOTE: additional request to fetch languages
$http.get("https://api.github.com/repos/" + $scope.search + "/" + $scope.repo + "/languages")
.then(function (response) {
console.log(response.data);
// TODO: display results
});
});
var user = $scope.search;
$scope.search = "mbostock";
// Make calls to the API for Users and Repo List
function initialFetch(){
$http.get("https://api.github.com/users/" + $scope.search)
.then(function(response){ $scope.userinfo = response.data; });
$http.get("https://api.github.com/users/" + $scope.search + "/repos")
.then(
function(response){
$scope.repolist = response.data;
// NOTE: select first repo
if ($scope.repolist && $scope.repolist.length > 0) {
$scope.repo = $scope.repolist[0].name;
}
},
$http.get("https://api.github.com/repos/" + $scope.search + "/" + $scope.repo + "/events")
.then(function (response) { $scope.eventinfo = response.data; })
);
}
// Function select which ensures that the entire
// text is selected when the user clicks in the text input.
$scope.select = function(){
this.setSelectionRange(0, this.value.length);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="container-fluid outerdiv" ng-app="myApp" ng-controller="DashboardCtrl">
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand"><b>Github User Information</b> <span class="span-style"></span></a>
</div>
<div class="input-group search-bar">
<input type="text" ng-model="search" ng-model-options="{ debounce: 800 }" onclick="select()" class="form-control" placeholder="Enter Github user login" autofocus />
<span class="input-group-addon bar-style"><i class="glyphicon glyphicon-search"></i></span>
</div>
</div>
</nav>
<noscript>
<div class="nojs">Javascript is either disabled or not supported in your browser. Please enable it or use a Javascript enabled browser.</div>
</noscript>
<div class="animated zoomInRight">
<div id="user-bio" class="col-sm-4 col-md-4">
<div>
<div class="avatar">
<img src="{{ userinfo.avatar_url }}" class="thumbnail animated flip movie-poster">
</div>
<span class="span-outer">
{{ userinfo.login }}
</span><br>{{ userinfo.name }}
<p><strong>Joined:</strong><br> {{ userinfo.created_at }}</p>
<p><strong>Last Updated:</strong><br> {{ userinfo.updated_at }}</p>
<p>{{ userinfo.bio }}</p>
<p class="outer-p">
<div class="inner-p">
<span class="label label-primary">Public Repos :</span> {{ userinfo.public_repos }}
</div>
<div class="inner-p">
<span class="label label-primary">Followers :</span> {{ userinfo.followers }}
</div>
<div class="inner-p">
<span class="label label-primary">Following :</span> {{ userinfo.following }}
</div>
</p>
</div>
<div ng-if="userinfo.message==='Not Found'">
No results found.
</div>
</div>
<div class="col-sm-8 col-md-8">
<h5><strong>Repositories:</strong></h5>
<!-- NOTE: use ng-model and ng-repeat and don't clobber repo variable on scope -->
<select id="repo-select" ng-model="repo">
<option ng-repeat="r in repolist" id="repo{{ $index + 1 }}" ng-value="r.name" onchange="MakeUrl();">{{ r.name }}</option>
</select>
<h5><strong>Events:</strong></h5>
<ul class="event-results" id="event-select" style="height:400px; overflow-y:auto;">
<li ng-repeat="event in eventinfo">
<a id="{{ $index + 1 }}" value="{{ event.type }}">{{ event.type }}
</a>, {{ event.created_at }} <!--ng-click="update(movie)"-->
</li>
</ul>
</div>
</div>
</div>

add 1 to value after submission to databse with angular

I'm working on a project where user can like comment made by users. and what i want to achieve is when a user likes a comment on a page by default + 1 should be added to the total comments made. Below is my script my it doesn't work
.controller('feedsctrl',['$scope','$http',function($scope,$http){
$http.get('http://localhost/vivalooks/app_ion/like.php').success(function(data){
//$scope.feeds = console.log(data) ;
$scope.feeds = data;
$scope.lovepic = function() {
event.preventDefault();
$http.post("http://localhost/vivalooks/app_ion/scripts/comment.php",
{
'u_pic_id': $scope.u_pic_id,
'pic': $scope.pic
}
).success(function(data,status,headers,config){
console.log(data)
$scope.comment_total=$scope.comment_total+1;
});
}
});
}])
HTML
<ion-content>
<div ng-controller="feedsctrl" class="list card has-subheader" ng-repeat="item in feeds">
{{item.comment_total}} Comments
</ion-content>
Issue with your code is that you are trying to update the $scope.data[item].comments with $scope.comments. These both are different variable in angular controller scope. you should perform the addition in the same scope variable to get it reflected on the view. You can achieve this by slight modification in your code
html
<ion-content>
<div ng-controller="feedsctrl" class="list card has-subheader" ng- repeat="item in feeds trach by $index">
<img src="item.src" ng-click="lovepic($index)">
{{item.comment_total}} Comments
</div>
</ion-content>
in the controller.
$scope.lovepic=function(index) {
event.preventDefault();
$http.post("http://localhost/vivalooks/app_ion/scripts/comment.php",
{'u_pic_id':$scope.feeds[index].u_pic_id,'pic':$scope.feeds[index].pic})
.then(function(data,status,headers,config){
$scope.feeds[index].comment_total == undefined ? 1 : $scope.feeds[index].comment_total +1;
});
}

How to display dynamic HTML in uib-popover inject into uib-grid

I want to display a dynamic generated HTML in uib-popover, and it's shown when a <i> is clicked in each column header of uib-grid. The ng directives and variables also need to be active, such as ng-click, $scope etc.
I tried to use the headerCellTemplate in each column definition of uib-grid for displaying the<i>tag, and I passed a dynamic generated HtML to each column definition, so that I can get it in the headerCellTemplate with col.displayName.popoverTemplate, It works fine. But I can't pass any variables in to popover use $scope, and ng-click don't work at all. Someone said I need to compile the HTML or use the uib-popover-template, how do I pass params to uib-popover-html or there is another way.
THANKS!
columnDefs
columnDefs.push({
name:'columnViewData._name',
displayName:{//use this file to pass params into uib-grid headers
displayName:'columnName',
popoverTemplate:generatePopoverTemplate(),//template should be shown in popover for this column header
customerScope:$scope//current scope, I hope popover can access it
},
width:100,
enableColumnMenu:false,
pinnedLeft:true,
headerCellTemplate:generateUIGridHeaderTemplate('name',0)
});
Column header template:
var generateUIGridHeaderTemplate = function(columnName,type){
return "\
<div role=\"columnheader\" ng-class=\"{ 'sortable': sortable }\" ui-grid-one-bind-aria-labelledby-grid=\"col.uid + '-header-text ' + col.uid + '-sortdir-text'\" aria-sort=\"{{col.sort.direction == asc ? 'ascending' : ( col.sort.direction == desc ? 'descending' : (!col.sort.direction ? 'none' : 'other'))}}\">\
<div style=\"margin-top:0.3em;\">\
<div style=\"display:inline;\" role=\"button\" tabindex=\"0\" class=\"ui-grid-cell-contents ui-grid-header-cell-primary-focus\" col-index=\"renderIndex\" title=\"TOOLTIP\">\
<span class=\"ui-grid-header-cell-label\" ui-grid-one-bind-id-grid=\"col.uid + '-header-text'\">\
{{ col.displayName.displayName CUSTOM_FILTERS }}\
</span> \
<span ui-grid-one-bind-id-grid=\"col.uid + '-sortdir-text'\" ui-grid-visible=\"col.sort.direction\" aria-label=\"{{getSortDirectionAriaLabel()}}\">\
<i ng-class=\"{ 'ui-grid-icon-up-dir': col.sort.direction == asc, 'ui-grid-icon-down-dir': col.sort.direction == desc, 'ui-grid-icon-blank': !col.sort.direction }\" title=\"{{isSortPriorityVisible() ? i18n.headerCell.priority + ' ' + ( col.sort.priority + 1 ) : null}}\" aria-hidden=\"true\">\
</i> \
<sub ui-grid-visible=\"isSortPriorityVisible()\" class=\"ui-grid-sort-priority-number\">\
{{col.sort.priority + 1}}\
</sub>\
</span>\
</div>\
<i style=\"margin-left:-1em;\" class=\"glyphicon glyphicon-filter\" popover-placement='bottom' uib-popover-html=\"col.displayName.popoverTemplate\" popover-title=\"Filter\" popover-append-to-body=\"true\">\
</i>\
<!-- above line is the popover togger shown in the column header-->\
</div>\
<div role=\"button\" tabindex=\"0\" ui-grid-one-bind-id-grid=\"col.uid + '-menu-button'\" class=\"ui-grid-column-menu-button\" ng-if=\"grid.options.enableColumnMenus && !col.isRowHeader && col.colDef.enableColumnMenu !== false\" ng-click=\"toggleMenu($event)\" ng-class=\"{'ui-grid-column-menu-button-last-col': isLastCol}\" ui-grid-one-bind-aria-label=\"i18n.headerCell.aria.columnMenuButtonLabel\" aria-haspopup=\"true\">\
<i class=\"ui-grid-icon-angle-down\" aria-hidden=\"true\">\
\
</i>\
</div>\
<div ui-grid-filter>\
</div>\
</div>"}
Popover template
var generatePopoverTemplate = function(){
var t = $sce.trustAsHtml('<a class="btn" ng-click="alert(\'asd\')">asd</a>');
$compile(t)($scope);
return t;
}
I solved my question :)
Generate the popover template and put it in to $compileCache with an Id then uib-popover-template property can find it and ng works fine.

Logic problems with AngularJS and multiple $http queries

I have an app that will make 2 $http queries to an external API and get 2 different JSON responses. These responses will populate a ng-repeat, headers, etc.
My problem is that I want to include a 3rd query, dependent on the first two.
Like so:
I get artist JSON and release JSON, and I use artist.name and release.title to populate the URL of the third $http query.
So far I've managed to get the two first queries, and once the results they are displaying in the ng-repeat, with ng-click I launch the 3rd query and populate an img ng-src.
Buuut, my problem is that I want the img ng-src to be populated automatically without ng-click, so the function that triggers the 3rd query has to get launched right after the 2 first queries. And also, in my working version right now, the img that I fetch with ng-click, will populate all items in ng-repeat. Meaning that every item should get their own image, and right now they don't.
I've created a working Plunker, if you search for a music artist and click on a result and then on an album, you'll see what I mean.
Basically, I think I'm missing a piece of logic that will put everything together and in proper trigger order.
Any thoughts?
My JS:
angular.module('myApp', ['ngResource'])
function Ctrl($scope, $http) {
var search = function(name) {
if (name) {
$http.get('http://api.discogs.com/database/search?type=artist&q='+ name +'&page=1&per_page=5').
success(function(data3) {
$scope.clicked = false;
$scope.results = data3.results;
});
}
$scope.reset = function () {
$scope.sliding = false;
$scope.name = undefined;
}
}
$scope.$watch('name', search, true);
$scope.getDetails = function (id) {
$http.get('http://api.discogs.com/artists/' + id).
success(function(data) {
$scope.artist = data;
});
$http.get('http://api.discogs.com/artists/' + id + '/releases?page=1&per_page=100').
success(function(data2) {
$scope.releases = data2.releases;
});
$scope.clicked = true;
$scope.sliding = true;
$scope.getImages = function (title, name) {
$http.get('http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=e8aefa857fc74255570c1ee62b01cdba&artist=' + name + '&album='+ title +'&format=json').
success(function(data4) {
$scope.images = data4;
});
}
}
};
My directive:
angular.module('myApp', ['ngResource'])
.directive('artistData', function() {
return{
restrict: 'E',
template: '<div class="col-md-8 col-md-offset-2"> \
<h1 ng-show="artist.name" class="artist-name">{{artist.name}}</h1> \
<div class="header-border" ng-show="artist.name"></div> \
<input ng-show="artist.name" class="form-control" ng-model="album" /> \
<div class="col-md-3" ng-click="getImages(release.title, artist.name)" ng-repeat="release in releases | filter:album | filter:{ role: \'main\' }"><div class="release">{{release.title}}<img class="img-responsive" ng-src="{{images.album.image[2][\'#text\']}}" /></div></div> \
</div>',
replace: true
};
})
And my HTML:
<div class="container">
<div class="row" ng-controller="Ctrl">
<div class="col-md-8 col-md-offset-2">
<div class="intro">
<div class="intro-text" ng-class="{'slide':sliding}">
<h1>Howdy stranger!</h1>
<h3>Use the form below to search for an artist and start building your record collection!</h3>
</div>
<input type="text" ng-model="name" class="form-control input-lg" ng-class="{'slide':sliding}" ng-focus="reset()" placeholder="Artist name"/>
</div>
<ul ng-hide="clicked" class="search-results">
<li ng-repeat="result in results" ng-click="getDetails(result.id)">{{result.title}}</li>
</ul>
</div>
<artist-data></artist-data>
</div>
</div>
I would use "Chaining Promises" in this case.
In basic words you call new async task on response of previous.
You can read this POST that might help you

Categories

Resources