Angular JS- Response from webservice not populating into list - json

I am very new to Angular JS and Ionic framework .
In services.js file, inside .factory method ,the webservice is invoked and can show the alert with the json response as shown in the screenshot below
But, the list view is not populated. I have tried in the two ways .
Try 01:
Angular JS code
angular.module('starter.services', [])
.factory('Chats', function($http) {
var chats;
return {
all: function() {
$http.get(url).
then(function(response) {
//alert(JSON.stringify(response.data.employee));
chats=response.data.employee;
alert(JSON.stringify(chats));
return chats;
}, function(error) {
alert(JSON.stringify(error));
});
return chats;
}
};
});
HTML5 code
<ion-view view-title="Chats">
<ion-content>
<ion-list>
<ion-item class="item-remove-animate item-avatar item-icon-right" ng-repeat="chat in chats" type="item-text-wrap">
<img ng-src="http://findicons.com/files/icons/820/simply_google/256/google_android.png">
<h2>{{chat.employeeCode}}</h2>
<p>{{chat.createdBy}}</p>
<i class="icon ion-chevron-right icon-accessory"></i>
<ion-option-button class="button-assertive" ng-click="remove(chat)">
Delete
</ion-option-button>
</ion-item>
</ion-list>
</ion-content>
</ion-view>
Try 2
In this try I have assigned the chats variable in the same file to the following array,
var chats = [{
id: 0,
name: 'Ben Sparrow',
lastText: 'You on your way?',
face: 'https://pbs.twimg.com/profile_images/514549811765211136/9SgAuHeY.png'
}, {
id: 1,
name: 'Max Lynx',
lastText: 'Hey, it\'s me',
face: 'https://avatars3.githubusercontent.com/u/11214?v=3&s=460'
}, {
id: 2,
name: 'Adam Bradleyson',
lastText: 'I should buy a boat',
face: 'https://pbs.twimg.com/profile_images/479090794058379264/84TKj_qa.jpeg'
}, {
id: 3,
name: 'Perry Governor',
lastText: 'Look at my mukluks!',
face: 'https://pbs.twimg.com/profile_images/598205061232103424/3j5HUXMY.png'
}, {
id: 4,
name: 'Mike Harrington',
lastText: 'This is wicked good ice cream.',
face: 'https://pbs.twimg.com/profile_images/578237281384841216/R3ae1n61.png'
}];
var chats = [{
id: 0,
name: 'Ben Sparrow',
lastText: 'You on your way?',
face: 'https://pbs.twimg.com/profile_images/514549811765211136/9SgAuHeY.png'
}, {
id: 1,
name: 'Max Lynx',
lastText: 'Hey, it\'s me',
face: 'https://avatars3.githubusercontent.com/u/11214?v=3&s=460'
}, {
id: 2,
name: 'Adam Bradleyson',
lastText: 'I should buy a boat',
face: 'https://pbs.twimg.com/profile_images/479090794058379264/84TKj_qa.jpeg'
}, {
id: 3,
name: 'Perry Governor',
lastText: 'Look at my mukluks!',
face: 'https://pbs.twimg.com/profile_images/598205061232103424/3j5HUXMY.png'
}, {
id: 4,
name: 'Mike Harrington',
lastText: 'This is wicked good ice cream.',
face: 'https://pbs.twimg.com/profile_images/578237281384841216/R3ae1n61.png'
}];
HTML5
<ion-view view-title="Chats">
<ion-content>
<ion-list>
<ion-item class="item-remove-animate item-avatar item-icon-right" ng-repeat="chat in chats" type="item-text-wrap">
<img ng-src="https://pbs.twimg.com/profile_images/514549811765211136/9SgAuHeY.png">
<h2>{{chat.name}}</h2>
<p>{{chat.lastText}}</p>
<i class="icon ion-chevron-right icon-accessory"></i>
<ion-option-button class="button-assertive" ng-click="remove(chat)">
Delete
</ion-option-button>
</ion-item>
</ion-list>
</ion-content>
</ion-view>
Try 2 is working as well as I have assigned hardcoded json array to the variable . But, Try 1 is not working .
UPDATE:
controller.js
angular.module('starter.controllers', [])
.controller('DashCtrl', function($scope) {})
.controller('ChatsCtrl', function($scope, Chats) {
$scope.chats = Chats.all();
})
/*.controller('ChatDetailCtrl', function($scope, $stateParams, Chats) {
$scope.chat = Chats.get($stateParams.chatId);
})*/
.controller('AccountCtrl', function($scope) {
$scope.settings = {
enableFriends: true
};
});
Please help me finding the solution .

You're not waiting for the promise to resolve in your controller.
Change your controller call of Chats.all() to:
Chats.all().then(function(chats) {
$scope.chats = chats;
});
Also, change the all function in your service to:
function all() {
return $http
.get(url)
.then(function(response) {
chats = response.data.employee;
return chats;
}, function(error) {
alert(JSON.stringify(error));
});
}

Related

Turning Vue route parameters into integers

I wanted to create my portfolio with Vue. I'm stuck with trying to turn the route params from a string into an id.
In the home page, my portfolio items are listed (doing this static-ally and using data objects and not getting from a database). When you click on them, route params take their id and it directs to /portfolio/1, /portfolio/2, and so on. This page then dynamically changes according to the data of that object.
There's also a pagination in this page (Next Project and Previous Project). Because I use their id as a parameter, I wanted to increment or decrement the ID on click so that it would lead to the next or previous project but I found out that the params are read as a string and not an integer, thus ending up with /portfolio/11 or /portfolio/21.
How can I implement this?
The code I've tried so far is as follows:
<router-link :to="{ name: 'Project', params: { id: `${previousFolio}` } }">
<b-button class="project-nav-button">
<img src="#/assets/icon-arrow-back.svg" alt="previous project button" class="previous"/>
<p>Previous Project</p>
</b-button>
</router-link>
<router-link :to="{ name: 'Project', params: { id: nextFolio } }">
<b-button class="project-nav-button">
<p>Next Project</p>
<img src="#/assets/icon-arrow-next.svg" alt="next project button" class="next"/>
</b-button>
</router-link>
data() {
return {
folioId: this.$route.params.id,
folios: [
{
id: 1,
title: "Project Title 1"
},
{
id: 2,
title: "Project Title 2"
},
{
id: 1,
title: "Project Title 3"
}
]
};
},
computed: {
currentFolio: function() {
let folioId = this.$route.params.id;
return this.folios.filter(function (folio) {
return folio.id == folioId;
})
},
nextFolio: function() {
let currentFolioId = this.$route.params.id;
currentFolioId = parseInt(currentFolioId);
return currentFolioId++;
console.log(currentFolioId);
},
previousFolio: function() {
let folioId = this.$route.params.id;
return folioId--;
},
Simply use the parseInt() to convert it to integer
let folioId = parseInt(this.$route.params.id);

Add "Select All'' button to ion-select

I'm using ionic 4 and I want to set custom buttons on ion-select through interfaceOptions
HTML
<ion-item>
<ion-label>Lines</ion-label>
<ion-select multiple="true" [(ngModel)]="SelectedLines" [interfaceOptions]="customAlertOptions">
<ion-select-option [value]="line" *ngFor="let line of Lines">{{linea.Name}}</ion-select-option>
</ion-select>
</ion-item>
TS
customAlertOptions: any = {
buttons: [
{
text: 'Select All',
handler: (blah) => {
console.log('Select All Clicked');
},
{
text: 'No',
handler: (blah) => {
console.log('Confirm Cancel: blah');
}
}, {
text: 'Okay',
handler: () => {
console.log('Confirm Okay');
}
}
]
};
However, only the default buttons are showing (Ok and Cancel)
Docs say it should be possible
https://ionicframework.com/docs/api/select
I can see this has been reported for previous versions of Ionic
https://forum.ionicframework.com/t/custom-button-for-ion-select-through-selectoptions-not-working/157305
Is it possible to make this work on Ionic 4? Is there a workaround?
EDIT: I tried with the PopOver interface with the same results
What you are trying to do isn't possible from what I can see.
The documentation actually only says you can set the buttons text:
ion-select#select-buttons - Ionic Documentation
By default, the alert has two buttons: Cancel and OK. Each button's text can be customized using the cancelText and okText properties.
It doesn't say that the buttons can be customised.
You can pass in the interfaceOptions but its overridden later by the default button set:
https://github.com/ionic-team/ionic/blob/master/core/src/components/select/select.tsx#L339
The code looks like this:
const alertOpts: AlertOptions = {
mode,
...interfaceOptions,
header: interfaceOptions.header ? interfaceOptions.header : labelText,
inputs: this.createAlertInputs(this.childOpts, inputType),
buttons: [
{
text: this.cancelText,
role: 'cancel',
handler: () => {
this.ionCancel.emit();
}
},
{
text: this.okText,
handler: (selectedValues: any) => {
this.value = selectedValues;
}
}
],
cssClass: ['select-alert', interfaceOptions.cssClass,
(this.multiple ? 'multiple-select-alert' : 'single-select-alert')]
};
return alertController.create(alertOpts);
So as you can see the ...interfaceOptions, is passed in at the start, then the buttons are set to the defaults, with the only customisation options being the ok or cancel text.
i am working with AlertController from ionic and i can custom it, just take a look at my screen .
You just need to import AlertController and after you can do something like this for exemple :
home.page.ts
async addAlertHome(adresse: string, lat: string, lon: string) {
const alert = await this.alertController.create({
header: 'Ajouter aux favoris',
message: 'Êtes vous sûr de vouloir ajouter cette adresse à vos favoris ?',
buttons: [
{
text: 'Non',
role: 'cancel',
cssClass: 'secondary'
}, {
text: 'Oui',
handler: () => {
alert.dismiss().then(() => {
this.addFavoriteHome(adresse, lat, lon);
});
console.log('Confirm Okay');
}
}
]
});
await alert.present();
}
And use it where you want on html :
home.page.html
<ion-icon name="heart-empty" (click)="addAlert(location.display_name, location.lat, location.lon)" end>
</ion-icon>
And don't forget on your constructor :
public alertController: AlertController

AngularJS: How to create routes with ui-router for my application

I have a problem with my a tag - I have a page that present data according to the GET vars.
For example - /foo.php?opt=1 will show table of cities that each one will go to - /foo.php?city=4 that have table of schools that go to /foo.php?school=4 that show table of students etc..
The problem is that the first time it works - when I choose city it will show me the list of schools and change the url, but when I choose school, it changes the URL but I still see the city table, and only if I press F5 it will show me table students.
This is the code:
odinvite.php:
<?php
if (isset($_GET['city']))
{
include "odbycity.php";
}
else if (isset($_GET['school']))
{
include "odbyschool.php";
}
else
{
include "odshowcities.php";
}
?>
odshowcities.php:
<div ng-controller="allcities">
<button class="btn btn-info" ng-repeat="x in names">
<a href="/odinvite.php?city={{x.areaid}}">
{{x.areaname}}</a>
</button>
</div>
odbyschool.php:
<div ng-controller="odbycity">
<button class="btn btn-info" ng-repeat="x in names">
<a href="/odinvite.php?school={{x.schoolid}}">
{{x.school_name}}</a>
</button>
</div>
MyAngular.js:
var myApp = angular.module('myApp',[]);
myApp.config(function( $locationProvider) {
$locationProvider.html5Mode(true);
});
myApp.controller ('allcities', function ($scope, $http)
{
$http.get("fetch_json_sql.php?option=1")
.then(function (response)
{
$scope.names = response.data.result;
});
console.log($scope.names);
});
myApp.controller ('odbycity', function ($scope, $http, $location)
{
$scope.cityid=$location.search().city;
console.log($scope.cityid);
$http.get("fetch_json_sql.php?option=2&cityid="+$scope.cityid)
.then(function (response)
{
$scope.names = response.data.result;
});
});
myApp.controller ('odbyschool', function ($scope, $http ,$location)
{
$scope.schoolid = $location.search().school;
console.log($scope.schoolid);
$http.get("fetch_json_sql.php?option=4&schoolid="+$scope.schoolid)
.then(function (response)
{
$scope.names = response.data.result;
});
});
What can be the problem?
I tried to make 100% change of the URL - link and it didn't work. just changed the URL without redirect.
Thanks!
You should stop rendering your templates with a backend. AngularJS is for SPA. If you need data provided by a backend try to implement an API e.g. a RESTful API. you need to configure your routes for example like in this runnable demo plnkr. It uses ui-router. Please note, this is just a demo. You should be able to put your logic into that prototype. I prepared all routes you need by using some dummy data. Just include your existing API in the controllers and you should be fine.
var myApp = angular.module("myApp", ['ui.router']);
myApp.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.when("", "/main");
$stateProvider
.state("main", {
url: "/main",
templateUrl: "main.html"
})
.state("main.listSchools", {
url: "/listSchools/:schoolId",
templateUrl: "schools.html"
})
.state("main.listAreas", {
url: "/listAreas/:areaId",
templateUrl: "areas.html"
});
});
myApp.controller('mainMenuController', function ($scope) {
$scope.schools = [{
schoolid: 1,
name: 'Test School 1'
},{
schoolid: 5,
name: 'Test School 5'
},{
schoolid: 11,
name: 'Test School 11'
}];
$scope.areas = [{
areaid: 3,
name: 'Test area 3'
},{
areaid: 7,
name: 'Test area 7'
},{
areaid: 19,
name: 'Test area 7'
}];
});
myApp.controller('listSchoolController', function ($scope, $state) {
$scope.schoolId = $state.params.schoolId;
});
myApp.controller('listAreaController', function ($scope, $state) {
$scope.areaId = $state.params.areaId;
});

understanding the ionic select

Im trying to use ionic list to display a set of cars, when the particular car is selected it should display a small description of it and also editable. Here Im unable to display the description of the item selected. Also please let me know how to edit the description and update it.
link here
this is the controller
car.controller('popSelect', ['$scope','$ionicPopup', function ($scope, $ionicPopup) {
$scope.homePage = function () {
window.location = "#/menu.html"
}
$scope.carList = [{ value: "Honda", description: "Its honda" },
{ value: "Toyota", description: "Its Toyota" },
{ value: "BMW", description: "Its BMW" }];
//$scope.carList=['Bmw','Mercedes','Honda'];
$scope.select_item = function (key) {
{{item.decription}}
}
}]);
Changes in Index.html
<body ng-app="myApp" ng-controller="myCtrl">
<h4>Select car</h4>
<ion-list>
<ion-item ng-click="select_item(value)" ng-repeat="(key,value) in carList">
{{value.value}}
</ion-item>
</ion-list><hr>
<div style="text-align:center">
<button class="button3" ng-click="showPopup()">ADD</button><hr>
<button class="button2" ng-click="homePage()">Back</button>
<button class=" button2" ng-click="deleteSelected()">Delete</button>
</div>
<div>{{description}}</div>
<!--{{couponTitle}} {{couponDescribe}} {{validFrom}} {{validTo}} -->
</body>
In your js
var car=angular.module('myApp',[]);
car.controller('myCtrl', ['$scope', function ($scope) {
$scope.homePage = function () {
window.location = "#/menu.html"
}
// $scope.description = '';
$scope.selectedItem = 'select';
$scope.items=[];
$scope.carList = [{ value: "Honda", description: "Its honda" },
{ value: "Toyota", description: "Its Toyota" },
{ value: "BMW", description: "Its BMW" }];
//$scope.carList=['Bmw','Mercedes','Honda'];
$scope.select_item = function (key) {
$scope.description=key.description;
}
}]);
Thanks (Y)

How to clear a Text Box in angularJS, when click any link in the page AngularJS

I've a search box and multiple categories links available in the HTML page.
as soon as user input in searchBox, i want to show:
p in Products | filter {serachedText}
When user clicks a category hyperlink, i want to show
p in Products | filter {categoryID}
But because serachedText is still avialble, result showing for
p in Products | filter {categoryID} | filter {serachedText}
Is there any way i can clear the serachedText as soon as user clicks on anylink.
That would be really easy to do in angularjs.
In html.
<input ng-model="mytext">
<a href ng-click="mytext=''">Clear Text</a>
jsfiddle is here.
Your filter expression is wrong.
if your data is a JSON array having category and name properties like so:
self.Products = [
{ category: 1, name: 'Pencil' },
{ category: 1, name: 'Notebook' },
{ category: 2, name: 'Kitten' }
];
And you are binding the following things for the selected category and search text:
self.category = 1;
self.searchText = 'pen';
You could create a complex filter expression like so:
filter: { category: vm.category | name: vm.searchText }
This will filter both on category and searchText or in combination.
To clear out the searchText, you can watch if category changes using $scope.$watch and when it changes, clear up the searchText.
Take a look at the example below or at http://plnkr.co/edit/OEDvOn. In the example, my filter expression is a bit more complicated since the selected category is actually an object containing value and name properties for the selected category, thus I need to add .value to get the right thing to pass to the filter.
Another point: For doing client side filtering, this is fine, but if you are filtering on server side, I'd rather get the filtering done on a service layer and just returned the filtered result instead of all possible data... save bandwidth and transfer time.
(function(undefined) {
'use strict';
angular.module('myApp',[]);
angular.module('myApp')
.controller('searchCtrl', searchCtrl);
searchCtrl.$inject = ['$log', '$scope'];
function searchCtrl($log, $scope) {
/* jshint validthis: true */
var self = this;
self.searchText = undefined;
self.categories = [
{ value: undefined, name: 'All' },
{ value: 1, name: 'Fruit' },
{ value: 2, name: 'Snacks' },
{ value: 3, name: 'Flower' },
{ value: 4, name: 'Pet' },
{ value: 5, name: 'Stationary' }
];
self.category = self.categories[0];
self.data = [
{ category: 1, name: 'Apple' },
{ category: 1, name: 'Grapes' },
{ category: 2, name: 'Dorito' },
{ category: 2, name: 'KitKat' },
{ category: 3, name: 'Roses' },
{ category: 3, name: 'Orchid' },
{ category: 4, name: 'Hamster' },
{ category: 4, name: 'Kitten' },
{ category: 5, name: 'Pencil' },
{ category: 5, name: 'Notebook' }
];
$scope.$watch(function() { return self.category; }, function(val, old) {
self.searchText = undefined;
});
}
}());
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="container" ng-app="myApp" ng-controller="searchCtrl as vm">
<div class="form-group">
<label>Category</label>
<select class="form-control" ng-options="cat.name for cat in vm.categories" ng-model="vm.category">
</select>
</div>
<div class="input-group">
<input class="form-control" type="textbox" ng-model="vm.searchText" placeholder="Search text here..." />
<span class="input-group-btn">
<button type="button" class="btn btn-primary">
<i class="glyphicon glyphicon-search"></i> Search</button>
</span>
</div>
<div class="well well-sm" style="margin-top:20px">
<ul ng-repeat="item in vm.data | filter:{category:vm.category.value, name:vm.searchText}">
<li>{{item.name}}</li>
</ul>
</div>
</div>
I'd suggest directive will be the best option
MarkUp
<input ng-model="mytext">
<a href ng-click="mytext=''" clear="mytext">Clear Text</a>
Directive
app.directive('a', function() {
return {
restrict: 'E',
scope: {
clear: '='
},
compile: function(scope, ele, attrs) {
ele.on('click', function() {
scope.$apply(function() {
scope.clear = undefined;
})
})
}
}
})