Pass scope to Service on AngularJS - javascript

I'm pretty new to AngularJS, I want to pass the scope to a service so I can perform a tag search based on the scope.value.
<div data-ng-app="instaSearch" data-ng-controller="search">
<div>
<input type="text" value={{value}} data-ng-model='value'/>
</div>
<p data-ng-hide="value">type a tag</p>
<p data-ng-show="value">...looking for {{value}}</p>
<ul>
<li data-ng-repeat="r in results">
<a>
<img ng-src="{{r.images.thumbnail.url}}" alt="" />
</a>
</li>
</ul>
</div>
Here is the JS
var app = angular.module('instaSearch', ['ngResource']);
app.factory('instagram', function($resource){
return {
searchTag: function(callback){
var api = $resource('https://api.instagram.com/v1/tags/:tag/media/recent?client_id=:client_id&callback=JSON_CALLBACK',{
client_id: '3e65f044fc3542149bcb9710c7b9dc6c',
tag:'dog'
},{
fetch:{method:'JSONP'}
});
api.fetch(function(response){
callback(response.data);
});
}
}
});
app.controller('search', function($scope, instagram){
$scope.$watch('value', function(){
$scope.results = [];
instagram.searchTag(function(data){
$scope.results = data;
});
});
});
working example

You can access the value using $scope.value.
app.factory('instagram', function ($resource) {
return {
searchTag: function (tag, callback) {
var api = $resource('https://api.instagram.com/v1/tags/:tag/media/recent?client_id=:client_id&callback=JSON_CALLBACK', {
client_id: '3e65f044fc3542149bcb9710c7b9dc6c',
tag: tag
}, {
fetch: {
method: 'JSONP'
}
});
api.fetch(function (response) {
callback(response.data);
});
}
}
});
app.controller('search', function ($scope, instagram) {
$scope.$watch('value', function () {
$scope.results = [];
instagram.searchTag($scope.value, function (data) {
$scope.results = data;
});
});
});
Demo: http://codepen.io/anon/pen/GHbIl

Related

Angular: ng-repeat calculate data in view

I am writing an angular website, but I have the following problem. I have 2 data arrays that I get from my json files.
I use an ng-repeat to go over my projects in my html file, and I use another ng-repeat to go over my projects.languages.
Now what I want to do is to make it that for every language I find I am going to search in the languages data
and get the other information.
How can I easly get the language in the ng-repeat, I need to also calculate in that the data maybe not avaible yet,
because I get the json data async.
This is the code I have right now:
<div class="container-fluid contentcontainer">
<div class="row">
<div class="col-xs-6 col-md-3" ng-repeat="project in projects">
<a href="#/project/{{$index}}" class="thumbnail">
<img ng-src="{{project.img}}" ng-alt="{{project.name}}" />
<div class="caption">
<div class="languageoverlay">
<span ng-repeat="language in projects[$index].languages">
<img ng-src="img/languages/android.png" ng-alt="{{language}}" />
<font ng-show="!$last">+</font>
</span>
</div>
<h3>{{project.name}}</h3>
</div>
</a>
</div>
</div>
</div>
<!--this is just to try, don't need to use this-->
<h1>{{getLanguage("CSharp")}}</h1>
App.js
app.service('projectService', ['$http', '$q', function($http, $q) {
var projectsDeferred = $q.defer();
var languagesDeferred = $q.defer();
$http({
method: 'POST',
url: 'json/projects.json',
cache: true
}).then(function(data) {
projectsDeferred.resolve(data.data.projects);
});
$http({
method: 'POST',
url: 'json/projects.json',
cache: true
}).then(function(data) {
languagesDeferred.resolve(data.data.languages);
});
this.getProjects = function(){
return projectsDeferred.promise;
};
this.getLanguages = function(){
return languagesDeferred.promise;
};
}]);
app.controller('ProjectsController', ['$scope', 'projectService', function($scope, projectService) {
$scope.projects = {};
$scope.languages = {};
var promise = projectService.getProjects();
promise.then(function(data) {
$scope.projects = data;
});
var promise = projectService.getLanguages();
promise.then(function(data) {
$scope.languages = data;
});
// This was a try, don't need to use this
$scope.getLanguage = function(name) {
array.forEach(function(element) {
if (element.name == name) {
$scope.push(element);
}
}, $scope.languages);
};
}]);
languages.json
{
"result":"SUCCESS",
"resultMessage":"",
"languages":[
{
"name":"CSharp",
"FullName":"C#",
"img":"img/languages/csharp.png"
},
{
"name":"Android",
"FullName":"Android",
"img":"img/languages/android.png"
},
{
"name":"VisualStudio",
"FullName":"Visual Studio",
"img":"img/languages/visualstudio.png"
}
]
}
projects.json
{
"result":"SUCCESS",
"resultMessage":"",
"projects":[
{
"name":"Test1",
"img":"img/projects/photo-1453060113865-968cea1ad53a.jpg",
"languages":["Android"]
},
{
"name":"Test2",
"img":"img/projects/photo-1454165205744-3b78555e5572.jpg",
"languages":["Android"]
},
{
"name":"Test3",
"img":"img/projects/photo-1457305237443-44c3d5a30b89.jpg",
"languages":["CSharp","VisualStudio"]
},
{
"name":"Test4",
"img":"img/projects/photo-1457612928689-a1ab27da0dad.jpg",
"languages":["CSharp","VisualStudio"]
}
]
}
Easy piece:
First don't use $q just use $http
app.service('projectService', ['$http', '$filter', function($http, $filter) {
function callLanguages(languages) {
return $http({
method: 'GET',
url: 'json/projects.json',
cache: true
}).then(function (response) {
return buildProjectWithLanguages(response.data.projects, languages);
});
}
function buildProjectWithLanguages (projects, languages) {
return projects.map(function (p) {
var langs = p.languages.map(function (l) {
var matchLangs = $filter('filter')(languages, { name: l });
if (matchLangs.length) {
return matchLangs[0];
} else {
return { FullName: l };
}
});
p.languages = langs;
return p;
});
}
this.getProjects = function(){
return $http({
method: 'GET',
url: 'json/languages.json',
cache: true
}).then(function(response) {
return callLanguages(response.data.languages);
});
};
}]);
then simplify your controller
app.controller('ProjectsController', ['$scope', 'projectService', function($scope, projectService) {
$scope.projects = [];
projectService.getProjects(function (projects) {
$scope.projects = projects;
});
}]);
and finally change your html to this:
<div class="container-fluid contentcontainer">
<div class="row">
<div class="col-xs-6 col-md-3" ng-repeat="project in projects">
<a href="#/project/{{$index}}" class="thumbnail">
<img ng-src="{{project.img}}" ng-alt="{{project.name}}" />
<div class="caption">
<div class="languageoverlay">
<span ng-repeat="language in project.languages">
<img ng-src="{{language.img}}" ng-alt="{{language.FullName}}" />
<font ng-show="!$last">+</font>
</span>
</div>
<h3>{{project.name}}</h3>
</div>
</a>
</div>
</div>
</div>
I really loved your awnser, but I made another approach with directives. I tested your awnser and it looks like a correct awnser.
This is what I did:
projects-directive.html
<div class="row">
<div class="col-xs-6 col-md-3" ng-repeat="project in projects">
<a href="#/project/{{$index}}" class="thumbnail">
<img ng-src="{{project.img}}" ng-alt="{{project.name}}" />
<div class="caption">
<languages languagenames="project.languages"></languages>
<h3>{{project.name}}</h3>
</div>
</a>
</div>
</div>
languages-directive.html
<div class="languageoverlay">
<span ng-repeat="language in languages">
<img ng-src="{{language.img}}" ng-alt="{{language.FullName}}" />
<font ng-show="!$last">+</font>
</span>
</div>
app.js
app.service('projectService', ['$http', '$filter', function($http, $filter) {
this.getLanguages = function() {
return $http({
method: 'GET',
url: 'json/languages.json',
cache: true
});
}
this.getProjects = function(){
return $http({
method: 'GET',
url: 'json/projects.json',
cache: true
})
};
}]);
app.directive('projects', ['projectService', function(projectService) {
return {
restrict: 'E',
templateUrl: "directives/projects-directive.html",
scope: {
limitto: "=?"
},
controller: function($scope)
{
projectService.getProjects().then(function(response) {
projects = response.data.projects;
if (angular.isDefined($scope.limitto))
{
$scope.projects = projects.slice(0, $scope.limitto);
} else {
$scope.projects = projects;
}
});
}
}
}]);
app.directive('languages', ['projectService', '$filter', function(projectService, $filter) {
return {
restrict: 'E',
templateUrl: "directives/languages-directive.html",
scope: {
languagenames: "="
},
controller: function($scope)
{
projectService.getLanguages().then(function(response) {
$scope.languages = $scope.languagenames.map(function (l) {
var matchLangs = $filter('filter')(response.data.languages, { name: l });
if (matchLangs.length) {
return matchLangs[0];
} else {
return { FullName: l };
}
});
});
}
}
}]);
app.controller('PortfolioController', ['$scope', 'projectService', function($scope, projectService) {
$scope.projectlimit = 4;
}]);
app.controller('ProjectsController', ['$scope', 'projectService', function($scope, projectService) {
}]);
How to call the directive:
<projects></projects>
and if you want to limit it, you can add parameter:
<projects limitto="projectlimit"></projects>

Cordova onloading with factory data

I'm trying to implement a display of loading message while data is being retrieved. In the case of basic js functions, it works, but in case of using factory to retrieve data, i dont get anything displayed before the data.
example of partial :
<div Class='' ng-controller="contentsCtrl">
<div ng-show="contents.news.length" class="">
<div ng-show="isloading"><br><img src="img/loader.gif" alt="" align='center'><br><br></div>
<ul id="tournois-list" ng-show="!isloading">
<li ng-repeat="content in contents.news track by $index">
<div class="tournois ">
<div class='row'>
<span class='contents_title'>{{content.content_title}}</span>
</div>
<div class='row'>
<span class='contents_dates'>{{content.content_date | date:'dd-MMMM-YYYY'}}</span>
</div>
<div class='row'>
<span class='contents_intro'>{{content.content_intro | htmlToPlaintext}}</span>
</div>
</div>
</li>
</ul>
</div>
</div>
code for controller + factory
baclyApp.controller('contentsCtrl',function($scope,contents){
$scope.isloading=true;
$scope.contents=contents.list();
console.log($scope.contents);
$scope.isloading=false;
})
baclyApp.factory("contents",function($http,$cookies){
var urlphp="http://bacly.fr/baclymphp/";
var contents={};
$http.get(urlphp+"getContent.php").then(function(response)
{
contents.news = response.data;
})
return {
list: function(){
return contents;
}
}
})
I guess this is about the timing as controller inject the factory object, so it needs to be resolved or something like this, but i don't know how to do it on another way.
Thanks !
Update : Here the other controller i'm talking about with multiple get
baclyApp.factory("tournois",function($http,$q){
//Factory qui recupère les données de tournois et iscriptions
// var urlphp="http://localhost/cordova/mbacly/www/php/";
var tournois={};
var urlphp="http://bacly.fr/baclymphp/";
$http.get(urlphp+"getTournois.php").then(function(response)
{
tournois.tournois = response.data;
console.log(tournois);
},function(status) {
alert("pas d acces réseau")
})
$http.get(urlphp+"getTournoinscriptions.php").then(function(response)
{
tournois.inscriptions = response.data;
},function() {
alert("pas d acces réseau")
});
$http.get(urlphp+"getTournoinscris.php").then(function(response)
{
tournois.inscris = response.data;
},function() {
alert("pas d acces réseau")
});
$http.get(urlphp+"getUsers.php").then(function(response)
{
tournois.users = response.data;
},function() {
alert("pas d acces réseau")
});
return {
list: function(){
return tournois;
},
find: function(cid){
return _.find(tournois.tournois, function(t) {return t.tournois_id === cid});
},
findinscris: function(cid){
return _.filter(tournois.inscris, function(t) {return t.tournois_id == cid});
},
findusers: function(uid){
return _.filter(tournois.users, function(t) {return t.user_id === uid});
},
findusersbyname: function(name){
return _.filter(tournois.users, function(t) {return t.uname === name});
},
updateinscription: function($params){
// var urlphp="http://localhost/cordova/mbacly/www/php/";
var urlphp="http://bacly.fr/baclymphp/";
var tournois={};
var retour="retour-OK";
$params_encoded =encodeURIComponent(JSON.stringify($params));
$http.get(urlphp+"saveinscription.php?data="+$params_encoded).success(function(data){
// console.log("retour-OK"+data);
retour="retour-OK";
});
return retour;
},
insertinscription: function($params){
// var urlphp="http://localhost/cordova/mbacly/www/php/";
var urlphp="http://bacly.fr/baclymphp/";
var tournois={};
var retour="retour-OK";
$params_encoded =encodeURIComponent(JSON.stringify($params));
$http.get(urlphp+"saveinscription.php?data="+$params_encoded).success(function(data){
// console.log("retour-OK"+data);
retour="retour-OK";
});
return retour;
},
deleteinscription: function($params){
// var urlphp="http://localhost/cordova/mbacly/www/php/";
var urlphp="http://bacly.fr/baclymphp/";
var tournois={};
var retour="retour-OK";
$params_encoded =encodeURIComponent(JSON.stringify($params));
$http.get(urlphp+"saveinscription.php?data="+$params_encoded).success(function(data){
// console.log("retour-OK"+data);
retour="retour-OK";
});
return retour;
}
}
})
Controller (part of):
baclyApp.controller('tournoisCtrl',['$scope','tournois','$cookies','$state','$window','growl',function($scope,tournois,$cookies,$state,$window,growl){
//Liste des tournois
$scope.showtournoislist=true;
$scope.tournois=tournois.list();
..
and later in the controller
tournois.findinscris(cid)
use this. $scope.isloading would be false, when comes response
baclyApp.controller('ContentsCtrl', function ($scope, ContentService) {
$scope.isloading = true;
ContentService.getContent("getContent.php", function (contents) {
$scope.contents = contents;
$scope.isloading = false;
}, function () {
$scope.isloading = false;
});
// contents.getContent("another.php", function (data) {
// $scope.contents = data;
// });
console.log($scope.contents);
});
baclyApp.service("ContentService", function ($http, $cookies) {
var urlphp = "http://bacly.fr/baclymphp/";
function getRequest(method, url, data, onSuccess, onError) {
var header = {}
$http({
method: method,
url: urlphp + url,
data: data
}).then(function () {
if (onSuccess) {
onSuccess(contents);
}
}, function () {
if (onError) onError();
});
}
function getContent(url, onSuccess, onError) {
getRequest("GET", url, null, onSuccess, onError);
}
function getOtherContent(url, onSuccess, onError) {
getRequest("POST", url, null, onSuccess, onError);
}
return {
getRequest: getRequest
getContent: getContent,
getOtherContent: getOtherContent
}
});
Also, I recommend that:
services, factories, controllers names should be capital letter. methods isn't.
use "service" to work with API.
use "factory" to transfer data among controllers.
UPDATED:
baclyApp.factory("tournois", function ($http, $q) {
//Factory qui recupère les données de tournois et iscriptions
// var urlphp="http://localhost/cordova/mbacly/www/php/";
var tournois = {},
urlphp = "http://bacly.fr/baclymphp/",
phpFiles = {
getTournois: "getTournois.php",
getTournoinscriptions: "getTournoinscriptions.php",
getTournoinscris: "getTournoinscris.php",
getUsers: "getUsers.php"
},
countResponse = 0;
function getDate(from, onSuccess, onError) {
$http.get(urlphp + from).then(function (response) {
if (response) {
if (onSuccess) {
onSuccess(response)
}
} else if (onError) {
onError()
}
}, function () {
onError();
})
}
getDate(phpFiles.getTournois, function (response) {
tournois.tournois = response.data;
countResponse++;
console.log(tournois);
}, function () {
alert("pas d acces réseau");
});
getDate(phpFiles.getTournoinscriptions, function (response) {
tournois.inscriptions = response.data;
countResponse++;
}, function () {
alert("pas d acces réseau");
});
getDate(phpFiles.getTournoinscris, function (response) {
tournois.inscris = response.data;
countResponse++;
}, function () {
alert("pas d acces réseau");
});
getDate(phpFiles.getUsers, function (response) {
tournois.users = response.data;
countResponse++;
}, function () {
alert("pas d acces réseau");
});
return {
getResponseAfterSuccess: function (onSuccess, onError) {
if (Object.keys(phpFiles).length == countResponse) {
if (onSuccess) onSuccess(tournois);
} else {
if (onError) onError(tournois);
}
},
list: function () {
return tournois;
}
//, more codes
}
});
baclyApp.controller('tournoisCtrl', ['$scope', 'tournois', '$cookies', '$state', '$window', 'growl', function ($scope, tournois, $cookies, $state, $window, growl) {
//Liste des tournois
$scope.showtournoislist = true;
$scope.isloading = true;
$scope.tournois = tournois.getResponseAfterSuccess(function (response) {
$scope.tournois = response;
$scope.isloading = false;
$scope.showtournoislist = false;
}, function (response) {
$scope.tournois = response;
});
}]);

content is loading everytime I refresh the page

I'm developing a simple CRUD application with MEAN stack. So the scenario is a user post a data to the server and it will render the data in real-time. Everything works fine but whenever I refresh the page ,
It will sort of loads all the content, every time it tries to fetch the data. I guess this is a caching problem.
So what I want to achieve is, every time a user refresh the page or go to another link, the content will be there without waiting for split seconds.
Here's the link to test it on, try to refresh the page
https://user-testing2015.herokuapp.com/allStories
and the code
controller.js
// start our angular module and inject our dependecies
angular.module('storyCtrl', ['storyService'])
.controller('StoryController', function(Story, $routeParams, socketio) {
var vm = this;
vm.stories = [];
Story.all()
.success(function(data) {
vm.stories = data;
});
Story.getSingleStory($routeParams.story_id)
.success(function(data) {
vm.storyData = data;
});
vm.createStory = function() {
vm.message = '';
Story.create(vm.storyData)
.success(function(data) {
// clear the form
vm.storyData = {}
vm.message = data.message;
});
};
socketio.on('story', function (data) {
vm.stories.push(data);
});
})
.controller('AllStoryController', function(Story, socketio) {
var vm = this;
Story.allStories()
.success(function(data) {
vm.stories = data;
});
socketio.on('story', function (data) {
vm.stories.push(data);
});
})
service.js
angular.module('storyService', [])
.factory('Story', function($http, $window) {
// get all approach
var storyFactory = {};
var generateReq = function(method, url, data) {
var req = {
method: method,
url: url,
headers: {
'x-access-token': $window.localStorage.getItem('token')
},
cache: false
}
if(method === 'POST') {
req.data = data;
}
return req;
};
storyFactory.all = function() {
return $http(generateReq('GET', '/api/'));
};
storyFactory.create = function(storyData) {
return $http(generateReq('POST', '/api/', storyData));
};
storyFactory.getSingleStory = function(story_id) {
return $http(generateReq('GET', '/api/' + story_id));
};
storyFactory.allStories = function() {
return $http(generateReq('GET', '/api/all_stories'));
};
return storyFactory;
})
.factory('socketio', ['$rootScope', function ($rootScope) {
var socket = io.connect();
return {
on: function (eventName, callback) {
socket.on(eventName, function () {
var args = arguments;
$rootScope.$apply(function () {
callback.apply(socket, args);
});
});
},
emit: function (eventName, data, callback) {
socket.emit(eventName, data, function () {
var args = arguments;
$rootScope.$apply(function () {
if (callback) {
callback.apply(socket, args);
}
});
});
}
};
}]);
api.js (both find all object and single object)
apiRouter.get('/all_stories', function(req, res) {
Story.find({} , function(err, stories) {
if(err) {
res.send(err);
return;
}
res.json(stories);
});
});
apiRouter.get('/:story_id', function(req, res) {
Story.findById(req.params.story_id, function(err, story) {
if(err) {
res.send(err);
return;
}
res.json(story);
});
});
For api.js whenever I refresh the page for '/all_stories' or go to a '/:story_id' it will load the data for split seconds.
allStories.html
<div class="row">
<div class="col-md-3">
</div>
<!-- NewsFeed and creating a story -->
<div class="col-md-6">
<div class="row">
</div>
<div class="row">
<div class="panel panel-default widget" >
<div class="panel-heading">
<span class="glyphicon glyphicon-comment"></span>
<h3 class="panel-title">
Recent Stories</h3>
<span class="label label-info">
78</span>
</div>
<div class="panel-body" ng-repeat="each in story.stories | reverse" >
<ul class="list-group">
<li class="list-group-item">
<div class="row">
<div class="col-xs-10 col-md-11">
<div>
<div class="mic-info">
{{ each.createdAt | date:'MMM d, yyyy' }}
</div>
</div>
<div class="comment-text">
<h4>{{ each.content }}</h4>
</div>
</div>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
<div class="col-md-3">
</div>
The loading problem you see is that the data is fetched after the view has been created. You can delay the loading of the view by using the resolve property of the route:
.when('/allStories', {
templateUrl : 'app/views/pages/allStories.html',
controller: 'AllStoryController',
controllerAs: 'story',
resolve: {
stories: function(Story) {
return Story.allStories();
}
}
})
Angular will delay the loading of the view until all resolve properties have been resolved. You then inject the property into the controller:
.controller('AllStoryController', function(socketio, stories) {
var vm = this;
vm.stories = stories.data;
});
I think you should use local storage. suited module - angular-local-storage
The data is kept aslong you or the client user clean the data,
Usage is easily:
bower install angular-local-storage --save
var storyService = angular.module('storyService', ['LocalStorageModule']);
In a controller:
storyService.controller('myCtrl', ['$scope', 'localStorageService',
function($scope, localStorageService) {
localStorageService.set(key, val); //return boolean
localStorageService.get(key); // returl val
}]);
Match this usage to your scenario (for example - put the stories array on and just append updates to it)

Retrieve data from three get resources by clicking fetch button once; angularjs

I want to get the data for three get URIs. In the form, the user enters a date which is used to retrieve three different datas from different URIs using the date user has entered. How ever this does not work. Below is my current code that I have written, but it does not work.
In simple words, The user selects a date, which is passed onto the URI and data is retrieved from the API, this happens in three functions, I want all three functions to run when the user clicks fetch.
HTML:
<div style="text-align: center" type="text/ng-template" ng-controller="DailyCtrl" class="users">
<h1>{{message}}</h1>
<form style="text-align: center" name="myform" id="myform1" ng-submit="fetch()" >
<input type="date"
ng-model="date"
value="{{ 'date' | date: 'dd/MM/yyyy' }}" />
<div><center><button type="submit" >Fetch</button></center></div>
</form>
{{formdata.date}}
<ul ng-controller="NewCooliosCtrl" ng-repeat="newCoolio in newCoolios.newCoolios">
<li>{{newCoolio.personID}}, {{newCoolio.placeID}}, {{newCoolio.datePlaced}}</li>
</ul>
<ul ng-controller="NewPlacesCtrl" ng-repeat="newPlace in newPlaces.newPlaces">
<li>{{newPlace}} </li>
</ul>
<ul ng-controller="NewUsersCtrl" ng-repeat="newUser in newUsers.newUsers">
<li>New Users: {{newUser}} </li>
</ul></br></br>
</div>
Angularjs:
myApp.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.when('/getdailydata', {
templateUrl: 'templates/getnewcoolios.html',
controller: 'DailyCtrl'
})
}])
.controller('DailyCtrl', function ($scope) {
$scope.toFetch = [];
$scope.fetch = function () {
for (var i = 0; i < $scope.toFetch.length; i++) {
$scope.toFetch[i]();
}
}
})
.controller('NewUsersCtrl', function ($scope, $http, $filter) {
$scope.fetch = function () {
var formdata = {
'date': $filter('date')(this.date, 'dd/MM/yyyy')
};
var inserturl = 'http://94.125.132.253:8001/getnewusers?date=' + formdata.date;
$http.get(inserturl).success(function (data) {
console.log(formdata);
$scope.newUsers = data;
console.log(inserturl);
console.log(data);
$scope.message = 'List of New Users';
})
}
$scope.toFetch.push($scope.fetch);
})
.controller('NewPlacesCtrl', function ($scope, $http, $filter) {
$scope.fetch = function () {
var formdata = {
'date': $filter('date')(this.date, 'dd/MM/yyyy')
};
var inserturl = 'http://94.125.132.253:8001/getnewplaces?date=' + formdata.date;
$http.get(inserturl).success(function (data) {
console.log(formdata);
$scope.newPlaces = data;
console.log(inserturl);
console.log(data);
$scope.message = 'List of New places';
})
}
$scope.toFetch.push($scope.fetch);
})
.controller('NewCooliosCtrl', function ($scope, $http, $filter) {
$scope.fetch = function () {
var formdata = {
'date': $filter('date')(this.date, 'dd/MM/yyyy')
};
var inserturl = 'http://94.125.132.253:8001/getnewcoolios?date=' + formdata.date;
$http.get(inserturl).success(function (data) {
console.log(formdata);
$scope.newCoolios = data;
console.log(inserturl);
console.log(data);
$scope.message = 'List of New Coolios';
})
}
$scope.toFetch.push($scope.fetch);
})
That should be in a service really as charlietfl pointed out - but can you not simplify the whole thing down and do something along the lines of (pseudo code!!!) :
.controller('DailyCtrl', function ($scope, $filter, $http) {
$scope.newCoolios = [];
$scope.newPlaces = [];
$scope.newUsers = [];
$scope.date;
$scope.fetch = function(){
var parsedDate = 'date': $filter('date')(this.date, 'dd/MM/yyyy');
$http.get('http://94.125.132.253:8001/getnewusers?date=' + parsedData.date).success(function (data) {
$scope.newUsers = data;
});
$http.get('http://94.125.132.253:8001/getnewplaces?date=' + parsedData.date).success(function (data) {
$scope.newPlaces = data;
});
$http.get('http://94.125.132.253:8001/getnewusers?date=' + parsedData.date).success(function (data) {
$scope.newUsers = data;
});
}
});
The the html could be something like....
<div style="text-align: center" type="text/ng-template" ng-controller="DailyCtrl" class="users">
<h1>{{message}}</h1>
<input type="date" ng-model="date" value="{{ 'date' | date: 'dd/MM/yyyy' }}" />
<button ng-click="fetch()">Update</button>
<ul ng-repeat="newCoolio in newCoolios">
<li>{{newCoolio.personID}}, {{newCoolio.placeID}}, {{newCoolio.datePlaced}</li>
</ul>
<ul ng-repeat="newPlace in newPlaces">
<li>{{newPlace}} </li>
</ul>
<ul ng-repeat="newUser innewUsers">
<li>New Users: {{newUser}} </li>
</ul>
</div>

Filtering AngularJS inside the scope

I'm trying to apply some sort of filter to my code but it's not changing anything when i click on the menu. I need to show all my albums initially and if the user clicks in one of te artists i want to filter them. Down here is my controller:
Function ListCtrl($scope, $http) {
$http({
method: 'GET',
url: 'json/json_price_1.json'
}).success(function(data) {
$scope.artists = data.artists; // response data
$scope.albums = [];
$scope.currentArtist = null;
$scope.setArtist = function(name) {
$scope.currentArtist = $scope.artists[name];
};
if ($scope.currentArtist == null) {
angular.forEach($scope.artists, function(element, index) {
angular.forEach(element.albums, function(album, index) {
$scope.albums.push(album);
});
});
} else {
angular.forEach($scope.currentArtist.albums, function(album, index) {
$scope.albums.push(album);
});
};
});};
My html is the following:
<div ng-controller="ListCtrl">
<ul class="topcoat-list" ng-repeat="artist in artists">
<li class="topcoat-list__item">
<a href="" ng-click="setArtist(artist.name)">
{{artist.name}}
</a>
</li>
</ul></div>
<div ng-controller="ListCtrl">
<ul ng-repeat="album in albums">
<li>{{album.title}}</li>
</ul>
Thanks for your time guys!
Not an expert in angularjs, the problem is you are not filtering the albums after the artist is set.
Function ListCtrl($scope, $http) {
$scope.setArtist = function (name) {
$scope.currentArtist = $scope.artists[name];
$scope.filter();
};
$scope.filter = function () {
$scope.albums = [];
if (!$scope.currentArtist) {
angular.forEach($scope.artists, function (element, index) {
angular.forEach(element.albums, function (album, index) {
$scope.albums.push(album);
});
});
} else {
angular.forEach($scope.currentArtist.albums, function (album, index) {
$scope.albums.push(album);
});
};
}
$http({
method: 'GET',
url: 'json/json_price_1.json'
}).success(function (data) {
$scope.artists = data.artists; // response data
$scope.currentArtist = undefined;
$scope.filter()
});
};
The angular solution will be is to use an filter - something like this demo

Categories

Resources