Setting up AngularJS template with API javascript - javascript

I am new to AngularJS and want to convert my current website to AngularJS. Below is a section of my webpage that shows meetings pulled from Google calendar. I am using the API to do this. My questions is how would I convert the HTML/Javascript to an AngularJS template? Do I just use a controller and dump all the javascript in it?
Currently my HTML shows the first two results in my calendar list.
This is my HTML:
<section class="sub-box meetings-box">
<div class="meetings-section">
<span class="meeting-h1">NEXT MEETING</span>
<div class="next-meetings-section">
<div class="meeting-info meeting-time next-meeting-time-start"></div>
<div class="meeting-info meeting-time next-meeting-time-end"></div>
<div class="meeting-info next-meeting-title"></div>
<div class="meeting-info next-meeting-location"></div>
</div>
<span class="meeting-h2">UPCOMING MEETINGS</span>
<div class="upcoming-meetings-section">
<div class="meeting-info meeting-time second-meeting-time-start"></div>
<div class="meeting-info meeting-time second-meeting-time-end"></div>
<div class="meeting-info second-meeting-title"></div>
<div class="meeting-info second-meeting-location"></div>
</div>
</section>
This is part of my Javascript that shows the callback response API
request.then(function(callbackResponse) {
var entries = callbackResponse.result.items; //returns an array entries
//get meeting info
var nextMeeting = entries[0];
var nextMeetingTimeStart = nextMeeting.start;
var nextMeetingTimeEnd = nextMeeting.end;
var nextMeetingTitle = nextMeeting.summary;
var nextMeetingLocation = nextMeeting.location;
var secondMeeting = entries[1];
var secondMeetingTimeStart = secondMeeting.start;
var secondMeetingTimeEnd = secondMeeting.end;
var secondMeetingTitle = secondMeeting.summary;
var secondMeetingLocation = secondMeeting.location;
//formatting info
for (var x in nextMeetingTimeStart && nextMeetingTimeEnd &&
secondMeetingTimeStart && secondMeetingTimeEnd) {
var nextMeetingStart = nextMeetingTimeStart[x];
var nextMeetingEnd = nextMeetingTimeEnd[x];
var secondMeetingStart = secondMeetingTimeStart[x];
var secondMeetingEnd = secondMeetingTimeEnd[x];
var nextMeetingStartFormat = new Date(nextMeetingStart).toString('hh:mm tt');
var nextMeetingEndFormat = new Date(nextMeetingEnd).toString('hh:mm tt');
var secondMeetingStartFormat = new Date(secondMeetingStart).toString('hh:mm tt');
var secondMeetingEndFormat = new Date(secondMeetingEnd).toString('hh:mm tt');
$('.next-meetings-section').find('.next-meeting-time-start').text(nextMeetingStartFormat+'-');
$('.next-meetings-section').find('.next-meeting-time-end').text(nextMeetingEndFormat);
$('.upcoming-meetings-section').find('.second-meeting-time-start').text(secondMeetingStartFormat+'-');
$('.upcoming-meetings-section').find('.second-meeting-time-end').text(secondMeetingEndFormat);
}
$('.next-meetings-section').find('.next-meeting-title').text(nextMeetingTitle);
$('.next-meetings-section').find('.next-meeting-location').text(nextMeetingLocation);
$('.upcoming-meetings-section').find('.second-meeting-title').text(secondMeetingTitle);
$('.upcoming-meetings-section').find('.second-meeting-location').text(secondMeetingLocation);

With Angular you would want to use a directive for DOM Manipulation, a factory (there are other options but this is a good starting place) for http calls and to store data. The controller should be concerned with providing scope for the view.
Angular Documentation:
controllers
directives
providers - factories are included here.
You may want to spend a few hours going through a tutorial or two before refactoring into Angular. Code School has a good one for free.
Edit-
Looking at your code you would want to take care of the server response inside a factory - create properties on your factory for nextMeeting and secondMeeting, and have them set to your server response data each time you get a server response back with the data.
Inject your factory into a controller, then in your controller you can have properties your view will use like: nextMeetingStart, nextMeetingEnd, etc. The value of these properties can be functions that use the values on your factory's nextMeeting and secondMeeting properties to set their appropriate return values.
Then you can just reference those properties in your view. The values displayed in the view will update whenever the factory receives new data from the server.

Related

Passing response with coverage.js produces error

I am using coverage.js for displaying data.
When I pass my variable (in which I get coverage response) into html file as we do it for angular to display expression,i t gives syntax error:
<div class="container" style="margin-top: 40px">
<div id="jsonAnswer" class="jsonAnswer" style="display: none">
{{coveragedetailjson}}
</div>
</div>
where coveragedetailjson is my variable where I get my response as a json
var data = $.parseJSON($("#jsonAnswer").html());
var coverage = new Coverage(data);
buildCoverageHTML = function (coverage) {
$(".coverage-section").remove();
var plugin = new CoveragePlugin(coverage);
// Adds the demographic section
plugin.addEligibleMetadataSection();
plugin.addDemographicsSection();
plugin.addInsuranceSection1();
plugin.addInsuranceSection2();
plugin.addInsuranceSection3();
plugin.addPlanMaximumMinimumDeductibles();
plugin.addPlanCoinsurance();
plugin.addPlanCopayment();
plugin.addPlanDisclaimer();
plugin.addAdditionalInsurancePolicies();
plugin.addGenericServices();
$('body').append(plugin.coverageSection);
};
buildCoverageHTML(coverage);
The above code in script tag
The fiddle I am using :
https://jsfiddle.net/Eligible/pqspk8gf/?utm_source=website&utm_medium=embed&utm_campaign=pqspk8gf
SyntaxError : Unexpected token {
Try changing
var data = $.parseJSON($("#jsonAnswer").html());
to use
var data = coveragedetailjson
instead of accessing DOM for this value.
In your case the variable {{coveragedetailjson}} is not updated/replaced with your JSON data when running the code.

Sorting out array of parent child relations where two children share a parent from an array and display it using div

I have the following data which gets served from a neo4j query, The data that gets sent back is in the format
home->parent->child1
home->parent->child2
home->parent2->child1
home->parent3->child1
home->parent3->child2
home->parent3->child3
I am trying to use javascript to display html which should be like this
<div id="parent1">
<div id="child1"></div>
<div id="child2"></div>
</div>
<div id="parent2">
<div id="child1"></div>
</div>
i tried loopong throigh the query and trying to get the parent to be the index of an object and the child to be values under it
i would do this like this in php
$jsonContents = (object)("parent"=>"child","parent"=>"child"....);
$array = array();
foreach($jsonContents as $jsCo=>$jsoCont){
$array[$jsoCont->parent][] = $jsoCont->child;
}
this would return the
$array as
home->parent1->[0]->child
->[1]->child
parent2->[0]->child...
This would let me avoid the check for uniqueness of the home parent category as well as put them in a hierarchy so i can interpret it properly in my View part of MVC, to create my div structure.
this is the url for the example json data
http://www.jsoneditoronline.org/?id=bdda268982eb431d361c25e9035bbc99
No answers to this, solved it by myself.
Here
var data = 'data shown in link above';
var myArr = [];
$.each(data, function(index, element) {
var parent = String(element.parent.properties.name);
var child = String(element.child.properties.name);
if(myArr[parent]){
myArr[parent][(myArr[parent].length)] = child;
} else {
myArr[parent] = Array(child);
}
});
Hope this helps people. :)

ng-repeat populating only after window click - AngularJS & PouchDB

I have the following function reading from a service:
var db = pouchService.db;
db.allDocs({startkey: 'move_', endkey: 'move_\uffff', include_docs: true})
.then(function (data) {
$scope.recordlist = data;
console.log($scope.recordlist);
});
Service:
angular.module('msfLogger').service('pouchService', PouchService);
function PouchService() {
var self = this;
self.db= new PouchDB('FleetDB');
};
On the front end, I'm trying to populate an ng-repeat from $scope.recordlist, but right now, when I load the page, the ng-repeat will be empty, and when I click anywhere on the page, it will get populated.
Also, when I add a new item in the DB, it will only show after page reload and click on window, not automatically.
<div class="row msf-row" ng-repeat="record in recordlist.rows">
<div class="col-md-1">{{record.doc.time}}</div>
<div class="col-md-1"><strong>{{record.doc.car}}</strong></div>
<div class="col-md-2">{{record.doc.driver}}</div>
<div class="col-md-2">{{record.doc.from}}</div>
...
</div>
What am I missing?
I think even if you have angular-pouchdb as a library, you need to inject it in the service, if not, you are using global PouchDB lib as normal and should be managing the $scope.$apply manually.
angular.module('msfLogger', ['pouchdb']).service('pouchService', PouchService);
function PouchService(pouchDB) {
var self = this;
self.db= pouchDB('FleetDB');
};

AngularJS + Firebase.util. How do I access data without knowing parent key?

Background:
When a delivery is created, an entry will be created under:
1- DELIVERIES->COMPANY->FIREBASEGENERATEDID->DELIVERY DETAILS
To allow users to track their purchases, they will have the delivery company and the unique ID of the delivery added to their profile.
2- USERS->DELIVERYTRACKING->COMPANY(delivery)->FIREBASEGENERATEDID(generated from deliveries above): TRUE
I am able to utilise Firebase.util.intersection to return an array of Firebase references, based on the use case above. However, when bound to a variable in $scope, I am unable to access the specific keys of the child object although I can display the lot to the view.
I've constructed a detailed JSFiddle which should explain the problem much more eloquently that I can by typing.
JSFiddle Link: http://jsfiddle.net/rwk1/8po8t35q/9/
SO required code:
<body ng-app="testApp" ng-controller="TestCtrl">
<div data-ng-repeat="tDelivery in trackedDelivery | orderByPriority">
<div class="profile-cards">
<p>{{tDelivery}}</p>
</div>
</div>
<br/><br/>
<h5>Question: How do I access the individual delivery details i.e. status?</h5>
</body>
'use strict';
var app = angular.module('testApp', [
'firebase'
]);
Controller:
app.controller('TestCtrl', function($scope, $firebase){
var fb = new Firebase('https://so0001.firebaseio.com');
var trackingRef = fb.child('users/Cara/deliveryTracking');
var trackingFb = $firebase(trackingRef);
trackingFb.$on('loaded', function(){
console.log(trackingFb.$getIndex());
});
var trackedDeliveryRefArray = [];
(function(){
trackingFb.$on('loaded', function(){
//console.log(trackingFb.$getIndex());
angular.forEach($firebase(trackingRef ).$getIndex(), function (k,v){
var trackedDeliveryRef = new Firebase.util.intersection(fb.child('users/Cara/deliveryTracking/' + k ),
fb.child('deliveries' + '/' + k ));
trackedDeliveryRefArray.push($firebase(trackedDeliveryRef));
});
});
})();
$scope.trackedDelivery = trackedDeliveryRefArray;
});
Result:
{"-randomFBKey1":{"company1":true,"name":"name value 1","status":"delivery 1 status"}}
{"-randomFBKey3":{"company2":true,"name":"delivery 3","status":"delivery 3 status"}}
Question: How do I access the individual delivery details i.e. status?
Structure:

Dijit.tree - how to update store URL

I have the following in my HTML file:
<div dojoType='dojox.data.XmlStore' id='navTreeStore' jsId='navTreeStore' url='' label='name'></div>
<div dojoType='dijit.tree.ForestStoreModel' jsId='navTreeModel' store='navTreeStore' query='{}' rootId='NavTree' rootLabel='NavTree' childrenAttrs='childNodes'></div>
<div dojoType='dijit.Tree' id='navTree' model='navTreeModel'></div>
I'd like to be able to alter the store's URL dynamically. I can't seem to be able to achieve that with the following:
var tree = dijit.byId('navTree');
tree.model.store.url = urlAddress; //new URL
tree.model.store.clearOnClose = true;
tree.model.store.close();
tree.model.store.fetch();
What am I missing?

Categories

Resources