Unable to display $scope in view - angularjs

I am querying a database and retrieving all the images belonging to the logged-in user, here is that code in uploadController:
UserImage.get($scope.user_id)
.success(function(data) {
$scope.userArray = data;
$location.path('/display');
});
I can console log the value of data and it is (first document):
0: Object
__v: 0
_id: "563bd07c7a49a7ac9ae1c513"
date: "2015-11-05T21:56:12.312Z"
gallery: "first gallery"
name: "1b0f6d56-9ed6-4412-a0d6-897a25fb3a84-460x360.jpeg"
user: "563bd0527a49a7ac9ae1c512"
so now I test that the target view (display.html) can receive the $scope.data:
<<div>{{userArray[0].name}}</div>
The $scope.userArray is not available to the display.html.
I tested the $scope in plunker and it worked ok:
http://plnkr.co/edit/q5XXnfl3JxkRdG0jLyps?p=preview
So I am a bit stumped.

first of all you should use ".then" instead of ".success" to use to promise system. If you want to know more about it
And i think your problem is also connected with $location.path('/display'); you ask your application to change location as soon as you get the answer, so it is probably loading another controller and stopping with your current one.

Related

Heap analytics - not seeing custom properties

I've implemented Heap analytics successfully and i'm seeing data come in.
The way I set a user is:
window.heap.identify(currentUser.id);
window.heap.addEventProperties({ platform_type: 'Web' });
if (currentUser.id) {
console.log('been here');
window.heap.addUserProperties({
'first_name': currentUser.first_name,
'last_name': currentUser.last_name,
'type': currentUser.type,
'country': currentUser.country,
'company_name': currentUser.company_name,
'role': currentUser.role,
'email': currentUser.email
});
}
I'm seeing the Email property data being recorded and associated (Email was a property already pre-defined by Heap), but i'm not seeing any of the other properties.
So, the addUserProperties call is working, but some data is being ignored.
Any idea what i'm doing wrong?
Thanks!
Uri
For anyone with the same problem, for me, the custom properties started appearing after a few hours..

Firebase Sync handling

I have data structure like below:
-Company
|
-jskdhjJKHh-Yty
-companyName:CompanyTH
-Employees
|
-shdjasjdshy665-333
|
-empName:Peter
|
-Company
-jskdhjJKHh-Yty:true
Im pushing data of Employees like below in ParentController:
Step 1:
var ref=firebase.database().ref("Employees");
var newKey=ref.push({empName:"John"}).key
Setup 2:
var childCompany=ref.child(newKey+'/Company');
childCompany.set(true);
Step 3:
$scope.emplist=$firebaseArray(ref);
In HTML:
<div ng-repeat="emp in emplist" ng-Controller="ChildController">
<p>{{emp.empName}}</p>
<p>{{CompanyName}}</p>
</div>
In ChildController:
var companyRef=firebase.database().ref("Company/"+Object.keys($scope.emp.Company)[0]);
$scope.CompanyName=$firebaseObject(companyRef);
Problem is :
When Step 1 executed it sync data to $scope.emplist and ChildController executed for that ng-repeat instance and when code in ChildController try to execute line Object.keys($scope.emp.Company)[0] it gives error that Company is not defined. This error is beacause Step 2 is not executed and firebase sync data after Step 1.But when Step 2 is executes it updates firebase-database but ChildController does not executes on updatation of ng-repeat instance.
One Solution in my mind that somehow Can I stop Firebase to sync data until all push queries finish? or any of you guys have any other solution?
One thing to note:
Above mentions steps executes successfully when I run it 2nd time again in same session of application, it is strange that it don't run in first attempt.
If I have understood your problem correctly, then you might have to change your push logic a bit.
Its always handy to save data in a specific node in Firebase in a single push command. As far as I can see, you're trying to push the data Employees node in two steps. Is it really necessary? You can easily push the empName and the childCompany at once using a single push.
And in your ChildController, you need to add a listener to that node from where you're trying to fetch the data using ref.on. So that you get a callback after a successful store of the data in your Firebase database.
var companyRef=firebase.database().ref("Company/"+Object.keys($scope.emp.Company)[0]);
companyRef.on("value", function(data) {
// This will be triggered once there's a
// change in data in the node the reference is referring to
doSomething();
});
Update
then how I can use set(true) within push?
Take a single object containing both empName and childCompany. Then just use push like this.
// Get the firebase reference of your node
var ref = firebase.database().ref("Employees");
// Create an object first.
var employee = {
empName: "Peter",
company: "CompanyTH"
};
// Pass the object that you've prepared earlier here.
ref.push.set(employee);
This is just an example. You can have nested object. The idea is to passing the whole object at once and add a callback on successful save in Firebase. You might think of something like this too.
ref.set(employee, function(error) {
if (error) {
doSomethingOnError();
} else {
doSomethingOnDataSavedSuccessfully();
}
});
You can try building nested classes like this
var employee = {
empName: "Peter",
Company: {
companyName: "Name",
uniqueID: true
}
};

Linking Data in Firebase

I am designing a forum and have a layout like this in on my Firebase:
root
|-posts
|-postID1
|-creator: "userOne"
|-creatorUID: "simplelogin:1"
|-text: "Some Text"
|-postID2
|-creator: "userTwo"
|-creatorUID: "simplelogin:2"
|-text: "Some Other Text"
|-profile
|-simplelogin:1
|-firstName: "John"
|-user: "userOne"
|-simplelogin:2
|-firstName: "Sue"
|-user: "userTwo"
On my forum page. I simply use a Angular ng-repeat to get all of the posts on Firebase and list them out. I also want to print out the first name of whoever created the post, but right now, I can only access {{ post.creator }}, which just gives the username of the person who posted. How can I link the post's creator (or creatorUID) with the first name field of that person's profile?
If you're just displaying the the users firstName I would place the users name in the postIDX object.
This would be quicker and produce less requests to Firebase with you going back and fourth with each post to get the usersFirst name.
more information on structuring data and best practices can be found here: https://www.firebase.com/docs/web/guide/structuring-data.html
Updated from response
if you wanted to get the user details then within every request to the postIDx you'd need to do something similar to this (not tested and quick mock up).
var fbRef = new Firebase('firebase path'),
postDetailsObject = {};
fbRef.child('posts').once('value', function(snapshot) {
// loop through each post
snapshot.forEach(function(childSnapshot){
var postDetails = childSnapshot.val(),
profileDetails;
postDetailsObject.post = postDetails;
fbRef.child('profile/' + postDetails.creatorUID).once('value', function(profileData) {
postDetailsObject.profile = profileData;
});
})
});
Then return the postDetailsObject in to angular so you can loop through the single object.

Backbone model's fetch doesn't work when the page initially loads but on second attempt works fine

In my backbone project I am trying to fetch a model based on some search criteria submitted by the users from a form. In submit handler, I am trying to fetch the model by passing search criteria's via data option (following is the code).
var productType=$("#productType").val();
var customerId=$("#customerId").val();
var stateSelected=$("#selectedState").val();
var srbStatus=$("#stateReportingStatus").val();
var dateType=$("#dateType").val();
var fromDate=$("#fromDate").val();
var toDate=$("#toDate").val();
var billTypeInd=$("#billTypeIndicator").val();
var dataElement=$("#dataElement").val();
var ediFileName=$("#ediFileName").val();
var ediBillName=$("#ediBillNumber").val();
var billId=$("#billId").val();
var claimantFirstName=$("#claimantFirstName").val();
var claimantLastName=$("#claimantLastName").val();
var insurerName=$("#insurerName").val();
var insurerFEIN=$("#insurerFEIN").val();
var insurerZip=$("#insurerZIP").val();
var dashboardSearchResultModel= new dashboardSearchResult();
var dashboardSearchResultModel= new dashboardSearchResult();
dashboardSearchResultModel.fetch({
data:{
productType: productType,
customerId: customerId,
state:stateSelected,
srbStatus:srbStatus,
dateType:dateType,
fromDate:fromDate,
toDate:toDate,
billTypeInd:billTypeInd,
dataElement:dataElement,
ediFileName:ediFileName,
ediBillName:ediBillName,
billId:billId,
claimantFirstName:claimantFirstName,
claimantLastName:claimantLastName,
insurerName:insurerName,
insurerFEIN:insurerFEIN,
insurerZip:insurerZip
},
wait:true,
success: function(dashboardSearchResultModel)
{
alert("This is what we get for result"+JSON.stringify(dashboardSearchResultModel));
$('#dashboardResultArea').html(self.dashboardResultTemplate({results:dashboardSearchResultModel.get("results")}));
},
error: function (model, xhr, options) {
alert("Error: An error occurred while trying to fetch the dashboardSearchResultModel");
alert("Error got model"+JSON.stringify(model));
alert("options:"+JSON.stringify(options));
alert("xhr:"+JSON.stringify(xhr));
}
});
Initially when the page loads after providing the search criteria's if I click submit the fetch doesn't work and goes to the error handler. After that when I submit the from second time the fetch works and retrieves data from the backend server. Any idea what is wrong? Thanks in advance.
When error callback is called, it is because your XHTMLRequest to the server returned a error (HTTP status code). So, there is where your problem resides.
Who starts this code? As the erros does not occur on a second attempt, I would suggest that you area callind $('#id').val() when the DOM is not ready. This way you are sending null values to the server, and that's causing the error you are receiving.
To solve your problem, assure you DOM is ready when executing this script.
See if your request is leaving the browser and reaching the server (i.e., cross-domain request fail with status 0, not reaching the server).
And, if it is, debug your server-side, as it does not seem to be an client-side problem.
So after trying many things I finally decided to try $.ajax call rather the fetch method. This is what I came up with
$.ajax({
type: "GET",
url: "rest/dashboardResult",
dataTyp: 'json',
data: {
productType: productType,
customerId: customerId,
state:stateSelected,
srbStatus:srbStatus,
dateType:dateType,
fromDate:fromDate,
toDate:toDate,
billTypeInd:billTypeInd,
dataElement:dataElement,
ediFileName:ediFileName,
ediBillName:ediBillName,
billId:billId,
claimantFirstName:claimantFirstName,
claimantLastName:claimantLastName,
insurerName:insurerName,
insurerFEIN:insurerFEIN,
insurerZip:insurerZip
}
})
.done(function(response) {
alert( "Result is: " + response);
});
This works without any problem from the get go. Now my question is how to bind the response to the backbone model?
Finally I figured out what was wrong. The call was inside a submit click handler, and $.ajax call or fetch is asynchronous. So by the time the call got reply from the server default action of submit click already took place (which is to reload the page). So by the time success or .done got called the whole page was reloaded. So I put event.preventDefault() at the beginning of handler method and let the handler receive the call back from the server and display it at the template. Thanks everyone for your time.

Backbone.js DELETE request not firing

I'm trying to get the backbone.js DELETE request to fire, but don't see any requests being made in my console.
I have collection model like so:
var Model = Backbone.Model.extend(
{
urlRoot: '/test',
defaults:{}
});
var TableList = Backbone.Collection.extend(
{
url: '/test',
model: Model
});
In my view I'm running this:
this.model.destroy();
Everything seems to be running fine, I can see output coming from the remove function that calls the destroy so I know it's getting there plus it also successfully runs an unrender method that I have. Can't see any requests being made to the sever though?
If I am not mistaken, you have to have an id property on your model to ensure that it hits the correct url. IE if your model was...
var Model = Backbone.Model.extend({
url: '/some/url'
});
var model = new Model({
id: 1
});
model.destroy(); // I THINK it will now try and DELETE to /some/url/1
Without an id it doesn't know how to build the url correctly, typically you'd fetch the model, or create a new one and save it, then you'd have a Url...
See if that helps!
I found the issue to my problem, thought not a solution yet. I'm not sure this is a bug with backbone or not, but I'm using ajaxSetup and ajaxPrefilter. I tried commenting it out and it worked. I narrowed it down to the ajaxSetup method and the specifically the use of the data parameter to preset some values.
Have you tried using success and error callbacks?
this.model.destroy({
success : _.bind(function(model, response) {
...some code
}, this),
error : _.bind(function(model, response) {
...some code
}, this);
});
Might be instructive if you're not seeing a DELETE request.

Resources