Selected city change on every page refresh and need to set again - angularjs

User from front page ,select the city from below list and as per search product are displayed.
But after the every product displayed , page reload and City selected get changed to First city and user need to select again city for every search.
Need help how to overcome this issue and set the city to user selected ,not refreshed every time .
//Define an angular module for our app
var app = angular.module('myApp', ['ui.bootstrap']);
app.controller('autocompleteController', function($scope, $http) {
$scope.cities = [
{name: 'London'},
{name: 'Paris'},
{name: 'Newyork'},
];
$scope.selectedCities = $scope.cities[0];
var initalizeproduct = function() {
$scope.products = $http.get("/getproduct/"+$scope.selectedCities.name).success(function(data){
$scope.products = data.products;
});
}
initalizeproduct($scope.products);
$scope.changeCity = function() {
initalizeproduct();
}
$scope.onSelectPart = function (item) {
$scope.selectedproducts = item;
window.location.href = "/product/"+$scope.selectedproducts.fields.slug;
};
});
From HTML Page :
<select ng-model="selectedCities" ng-change="changeCity()" ng-options="cities.name for cities in cities" style="background :transparent; border:0px; outline: none;">
</select>

Replace window.location.href = "..."; with:
$http
.get("/product/"+$scope.selectedproducts.fields.slug)
.then(function( ̶d̶a̶t̶a̶ response) {
var data = response.data;
// Get the HTML part from 'data' that you would like to display and add it to DOM
});
to begin with.

Related

Get JSON array object specific Id depending on which item i click on AngularJS

So i have a table with a list of teams, what i want to do is when i click on a team name it displays a new view with team details. There is 2 controllers, 1 to get league table and fixtures and then 1 for the team details. So far i have from the controller in the league table looped through the Json object array and gotten a list of links which contains the ID i need to pass in to the team details controller so i can specify which team it should display. Because the teams dont have the ID in the object i had to do it this way.
So the problem is that i can console.log all ID's but it only passes through the last ID logged. Which genereates the same team what ever team i click on. I want to get the specific ID for the team i click on and pass that to the team details controller id:.
I'm in the learning stages so excuse my poor code :).
If you see any improvements in my code writing please do let me know.
I get my data from:
http://api.football-data.org/
using the AngularJs factory library from:
https://github.com/JohnnyTheTank/angular-footballdata-api-factory
The View
<tbody>
<tr ng-repeat="team in teams.standing | filter:searchText | orderBy:orderByField:reverseSort">
// Where i want to somehow click on a team name and load that teams details
<td><strong>{{ team.teamName }}</strong></td>
</tr>
</tbody>
Controller1
.controller('AppCtrl', ['$scope', 'footballdataFactory', function($scope, footballdataFactory) {
$scope.date = new Date();
var apiKey = '***********************';
$scope.$back = function() {
window.history.back();
};
$scope.leagueId = function(id) {
$scope.id = id;
footballdataFactory.getLeagueTableBySeason({
id: $scope.id,
apiKey: apiKey, // Register for a free api key: http://api.football-data.org/register
}).success(function (data) {
$scope.teams = data;
$scope.leagueCaption = data.leagueCaption;
console.log("Get League", $scope.teams);
console.log('Loop through league and get team ids ----------------------------');
$scope.getTeamId = function(teamId) {
var dataLength = $scope.teams.standing.length;
for(var tUrl = 0; tUrl < dataLength; tUrl++) {
$scope.teamUrl = $scope.teams.standing[tUrl]._links.team.href.substr($scope.teams.standing[tUrl]._links.team.href.lastIndexOf('/') +1);
console.log('teamId: ' + $scope.teamUrl);
}
}
});
};
$scope.league = function(id) {
$scope.id = id;
footballdataFactory.getFixtures({
league: $scope.id,
apiKey: apiKey,
}).success(function(data){
$scope.games = data;
console.log("getFixtures", $scope.games);
});
};
}])
Controller2
// Team details controller
.controller('TeamCtrl', ['$scope', 'footballdataFactory', function($scope, footballdataFactory) {
var apiKey = '*************************';
footballdataFactory.getTeam({
id: $scope.teamUrl, ***Inserting the last 2 or 3 digits i get from the url***
apiKey: apiKey,
}).success(function(data){
$scope.teams = data;
$scope.name = data.name;
$scope.crestUrl = data.crestUrl;
$scope.squadMarketValue = data.squadMarketValue;
console.log("getTeam", $scope.teams);
});
footballdataFactory.getPlayersByTeam({
id: $scope.teamUrl,
apiKey: apiKey,
}).success(function(player){
$scope.players = player.players;
console.log("getPlayersByTeam", player);
});
}])
You can solve this problem easly with apiNG and the football-data plugin, that based on the same angular lib you even use. on the plugin page is a link to a working plnkr sample

Ionic return value to previous view

I am trying to create a form that works as follows:
Main View has list of all the fields
e.g 1. Merchant, 2. Amount 3. Date
The form is fairly long. Instead of doing a multistep form, I am hoping to do the following:
Tap on the Merchant to open a select merchant view and select merchant to return the value to main view.
Tap on Amount to enter amount view. Once the value is entered return the value to main view
Tap on date to enter the date view. Once the date is selected return int to the main view.
Any tips?
You can use a service to share data between the controllers associated with each view.
app.service('YourService', function($q) {
return {
details:
{
name: 'Merchant_1', //Some default values
amount: 100,
date: ""
}
,
getDetails: function() {
return this.details
},
setDetails: function(name,amount,date) {
this.details.name = name;
this.details.amount = amount;
this.details.date = date;
},
setName: function(name){
this.details.name = name;
}
}
});
and in your controllers inject 'YourService'. For eg. the controller for the merchant view.
app.controller( 'MerchantViewCtrl', function( $scope, YourService ) {
var onSelect = function(MerchantName){
YourService.setName(MerchantName);
}
});
Select Merchant view
<select ng-click="onSelect(merchant.name)" ng-options="merchant in merchantsList">
</select>
and in your main view controller
app.controller( 'MainViewCtrl', function( $scope, YourService ) {
var details = YourService.getDetails();
$scope.name = details.name;
$scope.amount = details.amount;
$scope.date = details.date;
});

AngularJs Typeahead directive not working

I have a simple requirement wherein a list of users is displayed and display a search button on top to search for the users by name, something like a simplified LinkedIn Connections page.
My web app is developed on node.js but this one page has been developed on angular.js and for this search button, I have decided to use the typeahead directive. This is how the jade file looks like:
html(ng-app='geniuses')
head
title List All Geniuses!
link(href='//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css', rel='stylesheet')
script(src='http://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js')
script(src="https://cdn.firebase.com/js/client/2.2.4/firebase.js")
script(src="https://cdn.firebase.com/libs/angularfire/1.1.2/angularfire.min.js")
script(src='js/listAllgeniuses.js')
body
div.container
div.page-header
h2 All Geniuses!
div(ng-app='geniuses',ng-controller='SearchAGenius')
input.form-control(placeholder='Genius',name='search-genius',ng-model="selected",typeahead="user for user in usersArr | filter:{'geniusid':$viewValue} | limitTo:8")
div(ng-app='geniuses',ng-controller='GetAllGeniuses')
ul
li(ng-repeat='user in users') {{ user.geniusid }}
The list of users are being fetched as an array from firebase. As you can see, the list of users is fetched using GetAllGeniuses controller and it works fine.. Here is the controller code:
(function (angular) {
var app = angular.module('geniuses', ["firebase"]);
app.controller('GetAllGeniuses', ["$scope", "$rootScope","$firebaseArray",
function($scope, $rootScope, $firebaseArray) {
var users = $firebaseArray(new Firebase("****));
$rootScope.usersArr = users;
$scope.users = users;
}
])
app.controller('SearchAGenius', ["$scope", "$rootScope",
function($scope, $rootScope) {
$scope.selected = '';
$scope.usersArr = $rootScope.usersArr;
}
])
}(angular));
This is how the data looks like(dummy):
[
{
geniusid: "new",
geniusname: ""
},
{
geniusid: "new",
geniusname: ""
},
{
geniusid: "news",
geniusname: ""
},
{
geniusid: "qazwsx",
geniusname: ""
}
]
I want to search using the geniusid (or name) in the search box... I have tried almost all ideas posted on the net but haven't been able to figure this out..
Any ideas would be appreciated.
Check out this Plunker I made using your demo.
A few things to note. You'll want to include Angular Bootstrap in your scripts and inject it into your module.
script(src='http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.13.0.min.js')
And
var app = angular.module('geniuses', ["firebase","ui.bootstrap"]);
Also, don't use $rootScope to pass data around. This is a prefect use for an angular service.
There's also no need to define ng-app everytime you're going to use angular.
Here's the rest of the plunker code that I modified to get this working.
html(ng-app='geniuses')
head
title List All Geniuses!
link(href='//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css', rel='stylesheet')
script(src='http://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js')
script(src='http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.13.0.min.js')
script(src="https://cdn.firebase.com/js/client/2.2.4/firebase.js")
script(src="https://cdn.firebase.com/libs/angularfire/1.1.2/angularfire.min.js")
script(src="./app.js")
body
div.container
div.page-header
h2 All Geniuses!
div(ng-controller='SearchAGenius')
input.form-control(placeholder='Genius',name='search-genius',ng-model="selected",typeahead="user as user.geniusname for user in usersArr | filter:{'geniusid':$viewValue} | limitTo:8")
div(ng-controller='GetAllGeniuses')
ul
li(ng-repeat='user in users') {{ user.geniusid }}
And the JS
(function(angular) {
var app = angular.module('geniuses', ["firebase", "ui.bootstrap"]);
app.controller('GetAllGeniuses', ["$scope", 'GeniusFactory',
function($scope, GeniusFactory) {
$scope.users = GeniusFactory.users();
}
]);
app.controller('SearchAGenius', ["$scope", 'GeniusFactory',
function($scope, GeniusFactory) {
$scope.selected = '';
$scope.usersArr = GeniusFactory.users();
}
]);
app.factory('GeniusFactory', ["$firebaseArray", function($firebaseArray) {
//Create a users object
var _users;
return {
users: users
}
function users() {
//This will cache your users for as long as the application is running.
if (!_users) {
//_users = $firebaseArray(new Firebase("****"));
_users = [{
geniusid: "new",
geniusname: "Harry"
}, {
"geniusid": "new",
"geniusname": "Jean"
}, {
"geniusid": "news",
"geniusname": "Mike"
}, {
"geniusid": "qazwsx",
"geniusname": "Lynn"
}];
}
console.log(_users);
return _users;
}
}]);
})(angular);

Reading data from firebase in angularfire

I have an app where I need to store artists and their details in database.Now I want to retrieve all the artists and render some of their details in front end.How to do that.
Secondly, if I get the artist rating in some input field by using ng-model, then how to store that value in a particular artist to update details.
The database structure is:
{
"artists": {
"Atif":{
"name":"atif",
"rating":8
},
"Himesh":{
"name":"himesh",
"rating":5
}
}
}
and this is angular.js
(function()
{
var app = angular.module("myapp", ["firebase"]);
app.controller("maincontroller", function($scope, $firebaseObject,$firebaseArray)
{
var ref = new Firebase("https://gigstart.firebaseio.com/");
var artists=ref.child("artists");
// download the data into a local object
$scope.data = $firebaseObject(ref);
// putting a console.log here won't work, see below
ref.on("value", function(snapshot)
{
console.log(snapshot.val());
}, function (errorObject)
{
console.log("The read failed: " + errorObject.code);
});
var artistsRef=new Firebase("https://gigstart.firebaseio.com//artists");
}); //end of controller
Now I want to render the name and rating of each artist in front end.Can I do something like
<div ng-repeat="artist in artists">
{{artist.name}}
{{artist.rating}}
</div>
You have a list of artists, which you want to ng-repeat over in your Angular view. You can accomplish that by:
app.controller("maincontroller", function($scope, $firebaseArray)
{
var ref = new Firebase("https://gigstart.firebaseio.com/");
var artists = ref.child("artists");
$scope.artists = new $firebaseArray(artists);
}
Please take a moment to go through the AngularFire quickstart before starting on your own project. This is covered in step 5.

how to filter arrays with local storage objects in angularjs?

I am new to Angularjs and am trying to build a news app in phonegap. In this app, a user can select categories such as sports, tech, etc (which are saved in local storage) and only news articles with those categories are displayed to the user. However, when a user selects the categories, they are being saved but I am lost as to how to compare those categories with the category from the news article(the news articles are being pulled from a external website in JSON format which has category along with title and description). Below is the code that I have so far. Any help can be greatly appreciated.
html code:
<div ng-repeat="new in news | limitTo: paginationLimit()">
<img ng-src="{{new.picture}}"alt="{{new.title}}" />
<b class="title">{{new.title}}</b>
<span class="catsource">{{new.category + ' | ' + new.source}}</span>
<p ng-model="letterLimit">{{new.body | limitTo:letterLimit }}...</p>
angularjs code:
app.controller('NewsController', function($scope, $http, NewsData) {
$scope.news = [];
var getData = function ($done) {
$http({method: 'GET', url: NewsData.url}).
success(function(data, status, headers, config) {
if ($done) { $done(); }
$scope.news = data.result;
$scope.letterLimit = NewsData.letterLimit; }); } };
The newsdata.url here is from data.js file which has all the data including url of the external website.
The code below is for categories controller where the categories selected are saved.
app.controller('HomeController', function($scope, Data, localStorageService) {
$scope.items = Data.items;
if (localStorageService.get('items')) {
$scope.items = localStorageService.get('items');
}
$scope.SaveCategories = function () {
localStorageService.clearAll();
localStorageService.add('items',$scope.items);
} )};
I am thinking maybe I can use a filter to filter out the selected categories but it did not work when I tried to do it. Thanks in advance.
if I understand what you want to achieve correctly is that you want to filter the news you receive as json to only include the categories the user has selected?
If so, do something like this:
add this to your NewsController
var filterNews = function(news) {
var k = news && news.length ? news.length : 0;
var i = 0;
var filters = localStorageService.get('items') || null;
var filteredNews = [];
if(!filters) {
return news;
}
//if filters is an array.
for(;i<k;i++) {
if(filters.indexOf(news[i].category) !== -1) {
filteredNews.push(news[i]);
}
}
//If filters is an object.
for(;i<k;i++) {
if(filters[news[i].category]) {
filteredNews.push(news[i]);
}
}
return filteredNews;
};
then call the function when you set this:
$scope.news = data.result;
to
$scope.news = filterNews(data.result);
and also note that you have to import the localStorageService to your NewsController as well
The best case would be if you could specify the categories in the request you make to return only the categories you want

Resources