Ionic 3 break data and show or angular trunk option - javascript

I am fetching some data from api, but their are some wordings, which are in single string. I need to show them seperately. Here is how it come in console:
And i want to show in my app like this:
This is already showing in other mobile application like this. But i want to know how it will done with ionic angular.
This is how im showing wording .
.ts
this.wording = this.res[0].policywording;
.html
<div *ngIf="wording">{{wording}}</div>
and the output is same as in console which is not in sequence i want to show it like as i attach . I think it is possible by trunk but dont know how ill use it .

You have to break up that data. Something like this:
ts:
this.displayData = [];
if (this.wording) {
const policies = this.wording.split('|').filter(w => w !== '');
this.displayData = [];
policies.forEach((policy) => {
const splited = policy.split('=');
const displayPolicy = {name: splited[0], value: splited[1]};
this.displayData.push(displayPolicy);
});
}
.html:
<div *ngIf="displayData && displayData.length > 0">
<div *ngFor="let policy of displayData">{{policy.name:}} {{policy.value}}</div>
</div>
<div *ngIf="!displayData || displayData.length === 0">No Data available</div>

Related

How can i hard code my data from realtime database?

So i have some data stored in a realtime datastore and only the admin can access the page where all the data is displayed, but how do i hard code the data to the website this is what i have and tried:
<!-- my html -->
<div v-for="(option, i) in reserveringen" :key="i">
{{ reserveringen[i] }}
</div>
data: function(){
return {
lidnummer: '',
reserveringen: []
}
},
mounted() {
self = this
const reserveringsref = firebase.database().ref('Reserveringen/')
reserveringsref.once('value', function(snapshot){
const lidnummer = ''
const reserveringen = []
snapshot.forEach(function(childSnapshot){
const data = childSnapshot.val()
self.lidnummer = data.Lidnummer
reserveringen.push(
"<tr><td>" + data.Lidnummer + "</td></tr>"
)
});
self.reserveringen = reserveringen;
});
},
This will only display the array i made as text. Can anyone help me with this issue or am i completely doing this wrong any advice will be thanked!
Your isue is not with RT-db but with Vue i guess;
If you want to build HTML in the JS section (as you do by pushing html tags inside an array), you should use the v-html directive instead of the interpolation.
Something like that
<div v-for="(option, i) in reserveringen" :key="i" v-html="reserveringen[i]">
</div>

Retrieve Firebase database specific value depending on key with angular 5

as the title says I build a CRUD application using Angular 5 and CRUD works just fine but now I need to retrieve a specific post data with advanced routing so the url should be something like :
https://example.com/blog/howtoDoSomething
and the page should contain this post details like name, content , image and so on .
I tried
details.component.ts
this.sub = this.route.params.subscribe(params => {
this.key = params['$key'];
});
details.component.html
<p>
this page about {{ $key }}
</p>
the above code worked fine with angular 4 with some difference of course and I used a json file not Firebase .
I also tried this one :
details.component.ts
var x = this.blogService.getData();
x.snapshotChanges().subscribe(item => {
this.blogList = [];
item.forEach(element => {
var y = element.payload.toJSON();
y["$key"] = element.key;
this.blogList.push(y as Blog);
});
});
details.component.html
<div *ngFor="let blog of blogList">
{{blog[$key].title}}
</div>
this one if I use blog alone like :
<div *ngFor="let blog of blogList">
{{blog}}
</div>
this retrieves the whole database as as
[object object] repeated
thanks in advance .
// user-service.ts
public getUser(userId: string) {
return this.afs.doc('users/' + userId).valueChanges();
)
// user-component.ts
// Get userId from route
this.user$ = this.userService.getUser(userId);
// user-component.html
<div *ngIf="user$ | async as user">
{{user | json}}
</div>

Angular 4 *ngFor, ngx-pipes get name of top-level key

I'm using the ngx-pipes in my ionic 3 app because I am pulling an object of objects from firebase.
I retrieve my objects and turn it into a variable that I can use on the page:
getEvents() {
this.firebaseDatabase.getEvents.subscribe(data => {
console.log("Events ", data);
this.events = data;
}, error => {
console.log("Events ", error);
});
}
I log the data and it comes back like this:
eventIDHashed_1:
endDateTime:"tomorrow"
location:"somewhere"
roles:
GyyapYhHQDOriruHLvGPKaTOiRp2:"admin"
startDateTime:"today"
title:"Arisss & Nathan"
type:"wedding"
eventIDHashed_2:
endDateTime:"tomorrow"
location:"somewhere"
roles:
GyyapYhHQDOriruHLvGPKaTOiRp2:"admin"
startDateTime:"today"
title:"Jack & Marlana"
type:"wedding"
The way I'm displaying it on the page is a temporary solution, but everything is working fine except the first line. I need to get the event name (the key) where it says eventIDHashed_1 and eventIDHashed_2
<div class="event-container">
<div *ngFor="let event of events | values; let i = index">
<span>{{events[i]}}</span>
<span>{{event.title}}</span>
<span>{{event.location}}</span>
<span>{{event.type}}</span>
<span *ngFor="let role of event.roles | pairs">
<span>{{role[0]}}, {{role[1]}}</span>
</span>
<span>{{event.startDateTime}}</span>
<span>{{event.endDateTime}}</span>
</div>
</div>
I have everything working and am able to retrieve all information, except the actual event ID <span>{{events[i] | keys}}</span> This gives me a list of all of the keys inside of it (endDateTime, location, title, startDateTime...), but I need to get the id of the event eventIDHashed_1 and eventIDHashed_2
After playing with ngx-pipes, I found that I could use the pairs operator fairly simply. I've changed the template from the above to this:
<div *ngFor="let event of events | pairs">
<span>{{event[0]}}</span>
<span>{{event[1].title}}</span>
<span>{{event[1].location}}</span>
<span>{{event[1].type}}</span>
<span *ngFor="let role of event[1].roles | pairs">
<span>{{role[0]}}, {{role[1]}}</span>
</span>
<span>{{event[1].startDateTime}}</span>
<span>{{event[1].endDateTime}}</span>
</div>
ngx-pairs gives me the key (position [0]) and the value (position [1]) of the event

AngularJS Voting System - Preventing Multi-Votes

I'm trying to create a voting system using AngularJS with the Ionic Framework. I'm using ng-repeat to loop over a series of user posts from a JSON array. Each post has an upvote and a downvote button. After one is selected, I have the button on that post disabled. The problem I'm currently experiencing is keeping that button disabled regardless if the user reopens the app. My goal is to prevent multi-voting. Currently, I'm using this method to disable the button after it's been clicked:
<button class="button button-small button-light" ng-click="upThread({{thread.id}})" ng-disabled="upDisabled[thread.id]">
<i class="icon ion-thumbsup"></i>
</button>
<button class="button button-small button-light" ng-click="downThread({{thread.id}})" ng-disabled="downDisabled[thread.id]">
<i class="icon ion-thumbsdown"></i>
</button>
$scope.upDisabled = {};
$scope.downDisabled = {};
$scope.upThread = function(id) {
...
$scope.upDisabled[id] = true;
$scope.downDisabled[id] = false;
}
$scope.downThread = function(id) {
...
$scope.downDisabled[id] = true;
$scope.upDisabled[id] = false;
}`
And this works great for disabling the buttons. Now, the problem is, I require Cache for the controller to be false, otherwise my new posts do not update in the view when added. This means, when reloading the app or switching between routes/views, the buttons become enabled again, which is not what I want. Additionally, setting cache to true doesn't keep the buttons disabled after the app has been reopened either.
I have tried using localstorage to store the $scope.upDisabled and $scope.downDisabled, but it ruins the JSON formatting. I have tried remote storage and received the same result. For example, the $scope.upDisabled and $scope.downDisabled store data like so:
{"2":true, "3":false, "4":true}
and so on. But because storing in localstorage or a database requires me to use JSON.stringify, you can guess that those quotes cause trouble and I end up with nested JSON as well. So, the data from localstorage does not return the correct format.
My known problems/options are twofold.
Is there a better solution to persistently disabling those
buttons?
How would I correctly format the JSON coming out of
localstorage?
Something else to note: Since this is a mobile/hybrid app using Ionic, I am not using cookies, but I did create a token system to act similarly.
Edit: Thanks to those who replied and your suggestions. I am currently using a MySQL database to keep track of the votes (May switch to SQLite later) #aorfevre: I've taken a look at the SQLite plugin before and will probably use it down the road. I finally got everything working how I want it to.
$scope.upDisabled = {};
$scope.downDisabled = {};
$scope.upCheck = {};
$scope.downCheck = {};
...Votes Loading function up here
...Thread loading Function up here
.finally(function(){
angular.forEach($scope.threads,function(value,index){
angular.forEach($scope.upCheck,function(value2,index){
if(value.id == value2.threadID)
{
$scope.upDisabled[value.id] = true;
$scope.downDisabled[value.id] = false;
}
})
})
angular.forEach($scope.threads,function(value,index){
angular.forEach($scope.downCheck,function(value2,index){
if(value.id == value2.threadID)
{
$scope.downDisabled[value.id] = true;
$scope.upDisabled[value.id] = false;
}
})
})
}
$scope.loadVotes();
$scope.loadThreads();
As for the server side (PHP with Laravel Framework):
public function upvoteThread($id, $token)
{
$thread = Thread::find($id);
$score = $thread->score;
$score = $score + 1;
$thread->score = $score;
$thread->save();
$voted = ThreadVote::where('threadID','=',$id)->where('token','=',$token)->get();
if($voted->isEmpty())
{
$upVote = new ThreadVote;
$upVote->threadID = $id;
$upVote->token = $token;
$upVote->upVote = 'true';
$upVote->downVote = 'false';
$upVote->save();
}
else
{
DB::table('thread_votes')
->where('threadID', '=', $id)
->where('token','=',$token)
->update(array('upVote' => 'true', 'downVote' => 'false')
);
}
return Response::json(array('status'=>1))->setCallback(Input::get('callback'));
}
public function getUpVotes($token)
{
$votes = ThreadVote::where('token','=',$token)
->where('upVote','=','true')
->select('threadID','upVote')
->get();
return Response::json($votes)->setCallback(Input::get('callback'));
}
...Similar downVote Function...
So as it stands. When the button is pushed, it saves the user's token, threadID, and vote to the database. When the view is loaded, that information, based on the token and threadID is loaded as a JSON array, associated with the Thread array and if a threadID and thread.id matches, it's pushed into the up/downdisabled scope as "threadID":bool ("1":true for example).
I'll recommand you to implement a DB if you manage huge volume of post.
I personnaly use localStorage for several preferences not for storing a db.
Therefore, if you target only for ios / android, I recommand you https://github.com/litehelpers/Cordova-sqlite-storage
If you target windows phone 8.1, the implementation is not trivial and I'm facing some issues regarding the structure of WindowsPhone & C++ compilation librairy ( more details here : https://issues.apache.org/jira/browse/CB-8866 )

multiple expression if else within ng-repeat

<div ng-repeat="book in books">
<h3 class="title">{{book.title}}</h3>
</div>
I use above code to get and it work fine, but I also have a search function, which will also set $scope.books. Unfortuunetly I have no control over the api, the search callback returned different scheme, means to get the title of the books I have to navigate to somewhere else, like book.category.item.title.
so I'm thinking of doing something like this
<a href="#/{{book.title || book.category.item.title}}">
check if book.title isset, else display another expression. Is it correct?
Instead I would prefer using ng-href
<a ng-href="{{getTitle()}}">link</a>
In your controller, return the url by checking logic there.
angular.module("app",[])
.controller("MainCtrl", function($scope) {
$scope.book = {};
$scope.book.title = null;
$scope.book.category = {
item : {
title : "Rafi"
}
}
$scope.getTitle = function() {
return '#/'+ ($scope.book.title || $scope.book.category && $scope.book.category.item && $scope.book.category.item.title);
}
});
DEMO
if you don't want to use controller for some reason:
<a ng-href="{{'#/'+(book.title || book.category.item.title)}}">

Categories

Resources