Angularjs, getting data from factory - javascript

I have a factory where i am trying to get data by $http service.
factory:
(function(){
angular
.module('projectApp')
.factory('weatherfactory', weatherfactory);
weatherfactory.$inject=['$http'];
function weatherfactory($http){
var cities=[
{name: "Łódź", link: "http://api.openweathermap.org/data/2.5/weather?q=Lodz,pl"},
{name: "Warszawa", link: "http://api.openweathermap.org/data/2.5/weather?q=Warszawa,pl"}
];
var weat={};
var service={
getCities: getCities,
GetWeather: _GetWeather
};
return service;
function _GetWeather(link){
$http.get(link).success(function(data){
weat=data;
});
return weat;
}
function getCities(){
return cities;
}
}
})();
In controller i call function from factory:
function weatherData(city){
sa.weather=weatherfactory.GetWeather(city);
sa.show=true;
}
View:
<div class="row">
<div class="col-md-8">
<select class="form-control" ng-model="sa.city">
<option ng-repeat="city in sa.cities" value="{{city.link}}">{{city.name}}</option>
</select>
</div>
<div class="col-md-4">
<button class="btn btn-primary" ng-click="sa.weatherData(sa.city)">Wybierz</button>
</div>
<div ng-if="sa.show">
{{sa.weather.name}}
</div>
</div>
It works but not correctly. I have to click button twice to show correct data.

When you make any server request you have to wait until the response is available in the callback function.
In your code you are right away returning from the function GetWeather so weat is empty for the first time. When you click the button second time the weather information is available by that time so you are able to see the weather information.
You have to do the below changes in your code.
Service change
function _GetWeather(link){
return $http.get(link);
}
Controller change
function weatherData(city){
weatherfactory.GetWeather(city).success(function (data) {
sa.weather = data;
sa.show = true;
});
}

Related

Dynamic routing depending on servers response in angularjs

So I am trying to configure my application in a way that lets it route dynamically depending on the servers response. My code is as follows.
HTML
<div ng-controller="CategoriesController" class="column">
<div layout-align="center center" ng-repeat="category in categories" >
<div class="category-button-text-english">{{category}}</div>
<md-button ng-click="submit()" class="category-button" aria-label="{{category}}">
<img ng-src="assets/images/categories/{{category}}.png"
alt="{{category}}">
</md-button>
<div class="category-button-text-translation">
{{category|uppercase| translate}}
</div>
Controller
$scope.submit=function(){
subCategoryService.getsubCategories().then(function (response)
{
console.log(response)
$rootScope.subcategories=response.data.data.subcategories;
$scope.category=response.data.data.category_name;
})
$location.path('/subcategory');
}
Service
.factory('subCategoryService', ['$http', '$httpParamSerializerJQLike', '$cookies','$rootScope', function ($http, $httpParamSerializerJQLike, $cookies,$rootScope,category){
var url2 = 'localhost:5000/api/subcategories/';
return {getsubCategories: function () {
return $http.get(url2);
}}}])
Another controller that gives the category names from server's response before the application comes on category page.
controller("userTypeController", function ($rootScope,$scope, $location, CategoryService) {
$scope.getCat=function(){
CategoryService.getCategories() .then(function (response)
{
$rootScope.categories=response.data.data.categories;
});
$location.path('/category');
};
So what I want is that after getting the category names from the server, it calls the right route depending on what button is clicked on the category page. For example depending on what button is clicked, the call should go like
localhost:5000/api/subcategories/CATEGORY_NAME. I get an array of categories when I go through the user type service and I want to use one of those category names to be passed in the subcategory service just as I wrote earlier. The flow of the application is like User->Category->Depending on category, show the subcategories. Any help would be appreciated. Thanks !!
Use like this
Route
.when("/category/:category_name", {
....
....
})
Service
.factory('subCategoryService', ['$http', '$httpParamSerializerJQLike', '$cookies','$rootScope', function ($http, $httpParamSerializerJQLike, $cookies,$rootScope,category){
var url2 = 'localhost:5000/api/subcategories/'+httpParamSerializerJQLike.category_name;
return {getsubCategories: function () {
return $http.get(url2);
}}}])

Event in Angular Controller Only Fires Once

I'm trying to implement an Angular version of an autocomplete textbox. I found some working examples, but none seem to exhibit the behavior I'm getting.
The autocomplete functionality itself works fine. When a suggested item is selected, the control correctly handles the selection. Subsequent uses of the control (typing in the autocomplete box, making a selection) fail to engage the 'selected' event/condition, although the autocomplete bit continues to work.
Here's my module & controller:
var app = angular.module('myapp', ['angucomplete-alt']); //add angucomplete-alt dependency in app
app.controller('AutoCompleteController', ['$scope', '$http', function ($scope, $http) {
//reset users
$scope.Users = [];
$scope.SelectedUser = null;
//get data from the database
$http({
method: 'GET',
url: '/UserRoleAdministration/Autocomplete'
}).then(function (data) {
$scope.Users = data.data;
}, function () {
alert('Error');
})
//to fire when selection made
$scope.SelectedUser = function (selected) {
if (selected) {
$scope.SelectedUser = selected.originalObject;
}
}
}]);
I'm guessing the problem is in there, but I don't know what it is. I include the bit from my view below, although there doesn't seem to be much there to fuss with:
<div class="form-group">
<div ng-app="myapp" ng-controller="AutoCompleteController">
<div angucomplete-alt id="txtAutocomplete" pause="0" selected-object="SelectedUser" local-data="Users" search-fields="RegularName" placeholder="People Search" title-field="RegularName" minlength="2" input-class="form-control" match-class="highlight"></div>
<!--display selected user-->
<br /><br />
<div class="panel panel-default" id="panelResults">
<div class="panel-heading"><h3 class="panel-title">Manage Roles for {{SelectedUser.RegularName}}</h3></div>
<div class="panel-body">
<div class="row">
<div class="col-md-2">
<img src="~/Images/avatar_blank.png" width="100%" />
</div>
<div class="col-md-4">
<div class="row">
<div class="col-md-4">Selected User:</div> <div class="col-md-6">{{SelectedUser.RegularName}}</div>
</div>
</div>
</div>
</div>
</div>
</div>
Any help would be appreciated!
UPDATE
After fixing the mistake Yaser pointed out, I wasn't getting any information regarding the selected object. So I set the page to output the entire object, rather than the specified fields, and I noticed I was getting information about the selected object, and on subsequent attempts as well.
So this worked: {{SelectedUser}}
This did not: {{SelectedUser.Department}}
Then I looked at the object and noticed its format. It had "title" and "description", and description had inside it the key/value pairs.
So now this works: {{SelectedUser.description.Department}}
And that's it.
Because the first time you are setting $scope.SelectedUser as a function but inside that you are rewriting the same one with an object. so next time it is not a function any more, try to rename the function:
$scope.setUser = function (selected) {
if (selected) {
$scope.SelectedUser = selected.originalObject;
}
}

How to display a returned json in angular view?

I am implementing a search in the github repository.
I need to display the information that i get from here: https://api.github.com/search/repositories?q=bootstrap . for instance into a view or HTML
<div ng-app="newsearchApp">
<div ng-controller="MainCtrl">
<form action="#/about" method="get">
<input ng-model="searchText" />
<button ng-click="search()">Search</button>
</form>
</div>
</div>
the code for searching the Github repository;
angular.module('newsearchApp')
.controller("MainCtrl", ["$scope", function($scope) {
$scope.searchText = "";
$scope.search = function() {
console.log($scope.searchText);
var item = $scope.searchText;
// console.log(item)
var GithubSearcher = require('github-search-api');
var github = new GithubSearcher({username: 'test#something.com', password: 'passwordHere'});
var params = {
'term': $scope.searchText
};
//i am not certain about the 'userData'
github.searchRepos(params, function(data) {
console.log(data);
$scope.userData = data; //i am not certain about the 'repoData'
});
} }]);
the problem is here, when populating the json object to HTML
<div ng-repeat="repo in userData | filter:searchText | orderBy:predicate:reverse" class="list-group-item ">
<div class="row">
<div class="col-md-8">
<h4>
<small>
<span ng-if="repo.fork" class="octicon octicon-repo-forked"></span>
<span ng-if="!repo.fork" class="octicon octicon-repo"></span>
<small>{{repo.forks_count}}</small>
</small>
<a href="{{repo.html_url}}" target="_blank" >
{{repo.name}}
</a>
<small>{{repo.description}}</small>
<small>{{repo.stargazers_count}}</small>
<a href="{{repo.open_issues_count}}" target="_blank" >
Open Issues
</a>
<small>{{}}</small>
</h4>
</div>
</div>
</div>
the results are null on the HTML but are not null on the console.
thanks in advance
the results are null
The problem is, that Angular doesn't notice that the GitHub server has answered and doesn't update the view. You have to tell Angular manually to re-render the view. Try calling $scope.$apply():
github.searchRepos(params, function(data) {
console.log(data);
$scope.userData = data;
$scope.$apply();
});
If you'd make your request to the GitHub API with Angulars $http service, then this would not be needed - you'll only need $scope.$apply() if something asynchronous happens which doesnt live in the "Angular world" - for example things like setTimeout, jQuery ajax calls, and so on. That's why there are Angular wrappers like $timeout and $http.
More details: http://jimhoskins.com/2012/12/17/angularjs-and-apply.html
The GitHub API can be accessed using the AngularJS $http service:
app.controller("myVm", function($scope,$http) {
var vm = $scope;
var url = "https://api.github.com/search/repositories?q=bootstrap"
$http.get(url).then(function onSuccess(response) {
vm.data = response.data;
console.log(vm.data);
})
})
HTML
<div ng-app="myApp" ng-controller="myVm">
<div ng-repeat="item in data.items">
{{item.full_name}}
</div>
</div>
The DEMO on JSFiddle
Since you're not using the Angular $http service, angular is not aware of the changes. You need to manually tell Angular to re-render and evaluate by using
$scope.$apply();

Angular JS === comparison not working

I am trying to compare the value passed from the url to a controller to a field in a json file.
galleryItem.html
<div class="filter-box">
<ul class="filter list-inline text-center" ng-repeat="gal in ParentData">
<li></li>
</ul>
</div>
<div class="container-fluid">
<div class="row">
<div class="portfolio-box" ng-repeat="x in data">
<div class="col-sm-4">
<div class="item-img-wrap">
<img ng-src={{x.url}} class="img-responsive" alt="">
<div class="item-img-overlay">
<a href={{x.url}} class="show-image">
<span></span>
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
The updated controller:
controllers.controller('GalleryViewCtrl', function GalleryViewCtrl($scope, $http, $stateParams) {
$scope.pageName = '';
$scope.Description = '';
$scope.GalleryID = $stateParams.id;
$http.get('/data/galleryItems.json')
.then(function (response) { $scope.ParentData = response.data.galleries });
$http.get('/data/galleryItemImages.json')
.then(function (response) {
$scope.data = response.data.images.galleryIdentifier === $stateParams.id;
});
});
I verified the correct value is being passed in to the controller, the values are static and so is the data being passed from the json file. I placed an if statement to check for null as suggested as well. I removed it temporarily to reduce what I'm working with.
If I remove the === $stateParams.id i get all of the images returned and displayed correctly.
If I replace $stateParams.id with a value that I know is in the list (4 or '4') i do not get anything returned. I also tried the value for the last item in the list.
There are no errors (loading scripts, reading json etc.) and all of the values are correct when I'm debugging.
I am still new to this and there is so much documentation with different solutions it all gets very confusing. If anyone has any ideas they would be greatly appreciated.
You are loading data to the $scope.data when the ajax call returns some data. I am assuming your view code is calling the galleryFiltered even before that. May be try to add a null check before returning the value from the method.
$scope.galleryFiltered = function () {
if($scope.data!=null)
{
return $scope.data.galleryIdentifier === $scope.GalleryID;
}
return false;
};
Remember that $http service returns a promise so your $scope.data will be undefined (or holding current state) until $http.get('/data/galleryItemImages.json') will return a success callback function and assign new value to $scope.data from response.
If you'll run $scope.galleryFiltered() before promise gets resolved you will have $scope.data == undefined or whatever data is stored on $scope.data at the time or $scope.galleryFiltered() execution.

Angular View not updating after retrieving data from database

I am currently working on an app that retrieves data on the of change of $routeParams. So here's how it begins:
function artistCtrl($scope, $http, $location, dataFactory, $routeParams){
$scope.artistName = $routeParams.artistname
$scope.$watch('artistName', function(newValue, oldValue){
$scope.artistInfo = dataFactory.getArtist(newValue)
})
$scope.artistInfo = {
artist_name: dataFactory.artistInfo.artist_name,
artist_genre: dataFactory.artistInfo.artist_genre,
artist_imageurl: dataFactory.artistInfo.artist_imageurl,
artist_bio: dataFactory.artistInfo.artist_bio
};
}
The callback for $watch here is run. dataFactory.getArtist retrieves newValue from my database which is being done successfully. That is done like this:
dataFactory.js
dataFactory.getArtist = function(artist){
return dataFactory.checkDb(artist).then(function(dbData){
if(dbData.data != "No data"){
dataFactory.artistInfo = dbData.data[0]
}
return dbData.data[0]
})
}
dataFactory.artistInfo = "";
dataFactory is a factory I created in another file.
artistpage.html
<div class="container this">
<div class="row">
<div class="col-sm-6">
<div><h1>{{artistInfo.artist_name}}</h1></div>
<div rate-yo id='stars' rating="myRating" class="col-sm-4"></div>
<div id='reviews'>23 Reviews</div>
<div><h2>{{artistInfo.artist_genre}}</h2></div>
<div><p>{{artistInfo.artist_bio}}</p></div>
<div><button type="button" class="btn btn-primary" ng-click="somefunc()">Submit a Review</button></div>
</div>
<div class="col-sm-6 reviews">
<div><img class="artistpageimage" src={{artistInfo.artist_imageurl}}></div>
</div>
</div>
</div>
I don't understand why my view isn't being updated. I am attempting to update $scope.artistName by assigning the returned dataFactory.getArtist(newValue)
and also by assigning the new data to dataFactory.artistInfo I have read about $apply, but I am having a hard time figuring out how to apply it in this context. Can anyone help?
Does getArtist return a promise or a value. If it's a promise try something like the below:
$scope.$watch('artistName', function(newValue, oldValue){
dataFactory.getArtist(newValue).then(function(value) {
$scope.artistInfo = value;
})
})
I think the problem is that dataFactory.getArtist(newValue) is returning a promise, which you're assigning directly to artistInfo. Try replacing it with:
dataFactory.getArtist(newValue).then(function (info) {
$scope.artistInfo = info;
});

Categories

Resources