This is my angular controller
//Save AddNewEmployee functionality
EDC.SaveNewEmployee = function () {
if (EDC.AddNewEmployeeFormValidator.validate()) {
var UserID = '0',
CandidateSubmit = '';
if (EDC.isEdit) {
UserID = EDC.rowIdToEdit;
}
EmployeeDetailService.SaveNewEmployee(EDC.NewEmpAdd, UserID, CandidateSubmit).then(function (response) {
//Close popup window
EDC.AddNewEmployeeWindow.data("kendoWindow").close();
//EDC.NewEmpSave = response;
EDC.EmployeeDetailsGrid.dataSource.read();
});
}
};
Andthis one is my MVC Controller.
public async Task<ActionResult> SavePermanentEmployee(Employee model)
{
//Sending mail to BU
string DisplayName = "New Employee";
//Sending mail to Employee
string EmpDisplayName = "Price credentials";
BAL_Employee objBalEmp = new BAL_Employee();
Price_PMS_DAL.Employee emp = new Price_PMS_DAL.Employee();
emp.ID = model.ID;
emp.EmpID = model.employeeID ?? Convert.ToString(model.employeeID).ToUpper();
emp.ReferredBy = model.referredby;
emp.DOJ = model.dateOfJoining;
emp.Status = 1;
emp.Email = model.email;
emp.BUID = model.businessUnitID;
emp.ShiftID = model.ShiftID;
emp.ModifiedBy = Session["EmpID"].ToString();
var lstNewEmployeeCreated = BAL_Employee.GetEmployees();
var result = lstNewEmployeeCreated.Where(s => s.employeeID == emp.EmpID).FirstOrDefault();
if (result != null)
{
return Json("Employee ID already exists.", JsonRequestBehavior.AllowGet);
}
else
{
int empSave = objBalEmp.UpdateEmployee(emp);
BAL_Login objBalLog = new BAL_Login();
if (empSave == 1)
{
TempData["Datarefresh"] = "refresh";
lstemp = null;
string[] datastr = emp.Email.Split(new string[] { "#" }, StringSplitOptions.None);
int empLoginSave = objBalLog.AddUser(new Price_PMS_DAL.Login { UserName = datastr[0].Trim(), EmpID = emp.EmpID, BUID = emp.BUID, ShiftID = emp.ShiftID });
if (empLoginSave == 1)
{
var data = BAL_Employee.FilterEmployeeByParam("Select TOP 1 * FROM Employee where Status=1 order by EmpID desc");
Price_PMS_DAL.Emp_Leave modelBal = new Price_PMS_DAL.Emp_Leave();
modelBal.EmpID = emp.EmpID;
int empLeavebalSave = objBalEmp.CreateEmployeeLLeaveBalRec(modelBal);
if (empLeavebalSave == 1)
{
Price_PMS_BAL.Models.BusinessUnit.BU Bus = BAL_BU.GetSPBUs().Where(b => b.ID == model.businessUnitID).First();
if (Bus != null)
{
//Sending Mail to BU when new Permanent employee added into the system
StringBuilder str = new StringBuilder();
StringBuilder cc = new StringBuilder();
StringBuilder to = new StringBuilder();
to.Append(#" " + Bus.BUHeadEmailId);
str.Append(#"Hello,<br><br> New Employee named <b>" + model.name + "</b> has been added to " + Bus.BUName + " BU " + " on " + DateTime.Now.ToShortDateString() + ".<br><br> Regards,<br> PRICE");
bool x = await Price_PMS_BAL.Models.Email.Email.SendEmail(cc, to, "New Employee Added", str.ToString(), DisplayName);
//End
}
//Sending Mail to Employee when new Permanent employee added into the system
if (emp != null)
{
StringBuilder str = new StringBuilder();
StringBuilder cc = new StringBuilder();
StringBuilder to = new StringBuilder();
to.Append(#" " + emp.Email);
//Username with last name Split
String[] Emailstring = emp.Email.Split(new[] { '#' });
String username = Emailstring[0];
//Username split with out last name
String[] Uname = username.Split(new[] { '.' });
String Unamestr = Uname[0];
Unamestr = Unamestr.Substring(0, 1).ToUpper() + Unamestr.Substring(1);
var PriceURL = "https://price.dreamorbit.com/";
str.Append(#"Hi " + Unamestr + ",<br><br> Welcome to DreamOrbit. Please login to PRICE (Projects, Resource Information & Cost Estimation) to apply for your leaves and to see your ratings etc. on a regular basis with following credentials:<br><br><br> <b><u>URL</u></b> : <a href=" + PriceURL + " target=_blank>" + PriceURL + "</a> <br> <b><u>Username</u></b> : " + username + "<br> <b><u>Password</u></b> : [Your System Password]<br><br><br> We wish you a long and mutually beneficial association with DreamOrbit. For any queries please reach out to Panchali (panchali.bharali#dreamorbit.com).<br><br> Regards,<br> PRICE");
bool x = await Price_PMS_BAL.Models.Email.Email.SendEmail(cc, to, "PRICE Credentials", str.ToString(), EmpDisplayName);
}
//End
return Json("Saved Successfully", JsonRequestBehavior.AllowGet);
}
else { return Json("Error occurred while saving data ", JsonRequestBehavior.AllowGet); }
}
else
return Json("Error occurred while saving data ", JsonRequestBehavior.AllowGet);
}
else
{
return Json("Error occurred while saving data ", JsonRequestBehavior.AllowGet);
}
}
}
Usually javascript code execute synchronously(default) and javascript has core promise object which is use to make function asynchronous.
Angularjs has core service $q which is use to make function asynchronous.
Angularjs simple example :
angular.module("starter", [])
.controller("myCtrl", function($scope, $q, $http){
var GetData = function(){
var root = 'https://jsonplaceholder.typicode.com';
var defer = $q.defer();
$http({
method: "GET",
url: root + '/posts/1'
}).then(function(response){
//success call back
defer.resolve(response);
}, function(error){
//error callbcall
defer.reject();
});
return defer.promise;
};
$scope.AsynchCall = function(){
GetData().then(function(response){
//success call back
console.log(response);
alert(JSON.stringify(response));
}, function(error){
//error callbcall
console.log(JSON.stringfy(error));
alert(error);
});
};
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-app="starter" ng-controller="myCtrl">
<button ng-click="AsynchCall()"> Asynch call </button>
</body>
</html>
This is because JSON.stringify will return the return value of the toJSON function if it exists.
Related
I have an AngularJS/MVC application that calls a MVC controller method. The method succeeds in sending an email but goes into the error function and the error variable is null.
Why is it failing?
I tried getting more on the error using a different call but the alert does not appear when using it. I guess because the return is null and can't be resolved.
Here is the AngularJS controller method.
$scope.BookMySeat = function (UserName, SeatNo) {
if (UserName) {
// The UserName is not empty. Check to see of it exists.
dataService.ValidateUsername(UserName).success(function (output) {
if (output == -1)
{
// The user name does NOT exist. Do the insert to the table.
$scope.onclick = !$scope.onclick;
console.log(UserName + SeatNo);
dataService.InsertSeat(UserName, slotNum, SeatNo).success(function (output) {
$scope.bookedSeatList = output;
var imageCollection = new Array(totalseat);
$scope.images = imageCollection;
$scope.imageUrlNotBooked = "../Images/RED.jpg";
$scope.bookcollscope = $scope.bookedSeatList;
console.log($scope.bookcollscope);
var imageCollection1 = new Array($scope.bookedSeatList);
$scope.images1 = imageCollection1;
$scope.imageUrlBooked = "../Images/GREEN.jpg";
// Alert.
alert("Seat number " + SeatNo + " has been booked for : " + UserName);
//----------------------------------------------------------------------------------------------------------
// Send an email using a MVC controller method.
// - Using $http to call to a MVC controller method.
//----------------------------------------------------------------------------------------------------------
var encodedQueryString = encodeURIComponent('emailAddress') + '=' + encodeURIComponent('dc4444#hotmail.com') + '&' + encodeURIComponent('type') + '=' + encodeURIComponent('I') + '&' + encodeURIComponent('seatNbr') + '=' + encodeURIComponent(SeatNo) + '&' + encodeURIComponent('slotNbr') + '=' + encodeURIComponent(0);
$http.get("/Home/SendAlertEmail?" + encodedQueryString).success(function (data) {
// Alert.
alert("An insert email was sent.");
}).error(function (error) {
// Error alert.
alert("Something went wrong with the insert - SendEmail. " + error);
console.log(error);
});
//$http.get("/Home/SendAlertEmail?" + encodedQueryString).success(function (data) {
// // Alert.
// alert("An insert email was sent.");
//}).error(function (xhr) {
// // Error alert.
// alert("Something went wrong with the insert - SendEmail. Status: " + xhr.status + ". Response Text: " + xhr.responseText);
// console.log(error);
//});
}).error(function (output) {
$scope.error = true;
});
}
else
{
// The user name exists.
alert("That passenger name exists. Please enter a UNIQUE passenger name in order to book a seat.");
}
console.log(output);
}).error(function (output) {
$scope.error = true;
});
}
else
{
alert("The passenger name is empty. Please enter a passenger name in order to book a seat.");
}
}
Here is the MVC controller method.
public void SendAlertEmail([FromUri] string emailAddress, [FromUri]string type, [FromUri]int seatNbr, [FromUri]int slotNbr)
{
string strHtmlMessageBody = "";
NetworkCredential NetworkCred = new NetworkCredential();
System.Net.Mail.SmtpClient smtp = new SmtpClient();
try
{
MailMessage mm = new MailMessage();
mm.From = new MailAddress("xxxxx#hotmail.com");
mm.Subject = "From the BookSeat Portal. Passenger Seat Information.";
if (type == "I")
{
strHtmlMessageBody = "<p>Your passenger seat: " + seatNbr + " has been created by the system.</p>";
}
else
{
strHtmlMessageBody = "<p>Your passenger seat number: " + seatNbr + ", slot number: " + slotNbr + " has been deleted by the system.</p>";
}
mm.Body = strHtmlMessageBody;
mm.IsBodyHtml = true;
mm.To.Add(new MailAddress(emailAddress));
smtp.Host = "smtp.live.com";
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = true;
smtp.Port = 587;
NetworkCred.UserName = "xxxxx#hotmail.com";
NetworkCred.Password = "yyyyyyy";
smtp.Credentials = NetworkCred;
smtp.Send(mm);
}
catch (SmtpException smtpEx)
{
throw new Exception("SMTP exception: " + smtpEx);
}
catch (Exception ex)
{
throw new Exception("Sending email exception: " + ex);
}
}
Here is the email sent.
here is my all code i am trying to upload small image and large image separate but angularjs not let me allow to do this, it only taking one file but not taking other one. plz anyone help with this. thanks in advance.
<div ng-app="eventModule" >
<div ng-controller="eventController">
<div>
<span >Thumbnail Image</span>
<input type="file" id="fileToUpload" onchange="angular.element(this).scope().selectThumbnail(this.files)" accept="image/*" />
</div>
<div>
<span >Large Image</span>
<input type="file" onchange="angular.element(this).scope().selectLargeImage(this.files)" class="LargeImageSubCategory" />
</div>
</div>
<span data-ng-click="SaveFile()">Submit</span>
</div>
<script>
var eventModule = angular.module('eventModule', []);
eventModule.controller('eventController', function ($scope,ArticleService, $http, $sce) {
$scope.selectThumbnail = function (file) {
$scope.SelectedThumbnail = file[0];
}
$scope.selectLargeImage = function (file) {
$scope.SelectedLargeImage = file[0];
}
$scope.SaveFile = function () {
$scope.IsFormSubmitted = true;
$scope.Message = "";
ArticleService.UploadFile($scope.SelectedThumbnail, $scope.SelectedLargeImage).then(function (d) {
alert(d.Message);
ClearForm();
}, function (e) {
alert(e);
});
};
});
eventModule.service("ArticleService", function ($http, $q) {
this.UploadFile = function (Thumbnail, LargeImage, TitleHeading, Topic, SmallDesc, LargeDesc) {
var formData = new FormData();
formData.append("Thumbnail", Thumbnail);
formData.append("LargeImage", LargeImage);
// here when i am trying to send two files so controller is not called
//and function is breaking and alert is comming "File Upload Failed"
formData.append("TitleHeading", TitleHeading);
formData.append("Topic", Topic);
var defer = $q.defer();
$http.post("/Articles/SaveFiles", formData,
{
withCredentials: true,
headers: { 'Content-Type': undefined },
transformRequest: angular.identity
}).success(function (d) {
defer.resolve(d);
}).error(function () {
defer.reject("File Upload Failed!");
});
return defer.promise;
}
});
</script>
//And My ArticlesController.cs code is
[HttpPost]
public JsonResult SaveFiles(string TitleHeading, string Topic)
{
string Message, fileName, actualFileName;
Message = fileName = actualFileName = string.Empty;
bool flag = false;
if (Request.Files != null)
{
var file = Request.Files[0];
actualFileName = file.FileName;
fileName = Guid.NewGuid() + Path.GetExtension(file.FileName);
int size = file.ContentLength;
try
{
file.SaveAs(Path.Combine(Server.MapPath("~/UploadedFiles"), fileName));
using (TCDataClassesDataContext dc = new TCDataClassesDataContext())
{
Article insert = new Article();
insert.ArticleId = Guid.NewGuid();
insert.TitleHeading = TitleHeading;
insert.SmallImagePath = fileName;
dc.Articles.InsertOnSubmit(insert);
dc.SubmitChanges();
Message = "File uploaded successfully";
flag = true;
}
}
catch (Exception)
{
Message = "File upload failed! Please try again";
}}
return new JsonResult { Data = new { Message = Message, Status = flag } };
}
You are appending the files to the formdata, thus you need to specify the Thumbnail and LargeImage as parameters of your MVC controller. Please see below:
[HttpPost]
public JsonResult SaveFiles(
HttpPostedFileBase thumbnail
, HttpPostedFileBase largeImage
, string titleHeading
, string topic)
{
string Message, fileName, actualFileName;
Message = fileName = actualFileName = string.Empty;
bool flag = false;
if (thumbnail != null && thumbnail.ContentLength != 0)
{
SaveFile(thumbnail);
}
if (largeImage != null && largeImage.ContentLength != 0)
{
SaveFile(largeImage);
}
return new JsonResult { Data = new { Message = Message, Status = flag } };
}
private void SaveFile(
HttpPostedFileBase httpFile)
{
var actualFileName = httpFile.FileName;
var fileName = Guid.NewGuid() + Path.GetExtension(httpFile.FileName);
int size = httpFile.ContentLength;
try
{
httpFile.SaveAs(Path.Combine(Server.MapPath("~/UploadedFiles"), fileName));
using (TCDataClassesDataContext dc = new TCDataClassesDataContext())
{
Article insert = new Article();
insert.ArticleId = Guid.NewGuid();
insert.TitleHeading = TitleHeading;
insert.SmallImagePath = fileName;
dc.Articles.InsertOnSubmit(insert);
dc.SubmitChanges();
Message = "File uploaded successfully";
flag = true;
}
}
catch (Exception)
{
Message = "File upload failed! Please try again";
}
}
have a some data one my page that is in a ng-repeat.
When the page and data 1st loads the data shows up.
When I move away from the page (using Angular Routing) make a change to the data (gets saved in db) then come back into the page (make call to db get new data) the ng-repeat data does not refresh. I can see the new data loading into the array and it is the new data.
I start the process on the page with
var sp = this;
sp.viewData = [];
sp.employee = [];
sp.ViewDataTwo = [];
$(document).ready(function () {
var testHeader = setInterval(function () { myTimer() }, 1000);
function myTimer() {
if (addHeaderToken() != undefined) {
clearInterval(testHeader);
sp.usageText = "";
if (sessionStorage.getItem(tokenKey) != null) {
sp.associatedInfo = JSON.parse(getassociatedInfo());
loadDataOne();
loadDataTwo();
}
}
}
});
I do this because I need to get my security toke from a JS script that I have no power over changes. So I need to make sure the code has ran to get me the token.
here are the functions I call..
function loadPasses() {
$http.defaults.headers.common.Authorization = "Bearer " + addHeaderToken();
$http.get('/api/Employee/xxx', { params: { employeeId: sp.employeeId } }).then(function (data) {
sp.viewData = data.data;
for (var i = 0; i < $scope. viewData.length; i++) {
sp.passes[i].sortDateDisplay = (data.data.status == "Active" ? data.data.DateStart + "-" + data.data[i].DateEnd : data.data[i].visitDate);
sp.passes[i].sortDate = (data.data[i].status == "Active" ? data.data[i].DateStart: data.data[i].visitDate);
}
});
}
function loadDataTwo () {
$http.defaults.headers.common.Authorization = "Bearer " + addHeaderToken();
if (sessionStorage.getItem(tokenKey) != null) $http.get('/api/Employee',
{
params: { employeeId: sp.employeeId }
}).then(function (data) {
sp.employee = data.data;
var tempPassString = "";
sp.ViewDataTwo = [];
var totalA = 0;
var totalU = 0;
for (var p = 0; p < sp.employee.dataX.length; p++) {
sp.ViewDataTwo.push(sp.employee.dataX[p].description + "(" + /** math to update description **// + ")");
totalA += parseInt(parseInt(sp.employee.dataX[p].Anumber));
totalU += parseInt(sp.employee.dataX[p].Bnumber));
}
sp.usageArr.push(" Total: " + totalA- totalU) + "/" + totalA + " Available");
//$scope.$apply();
});
}
One my view sp.viewData and sp.ViewDataTwo are both in ng-repeats.
Works well on load.. when I go out and come back in. I see the data reloading. But the view does not.
I have hacked the Dom to get it to work for now. But I would like to do it the right way..
Any help.
I have used
$scope.$apply();
But it tells me the digest is already in process;
the views are in a template..
Please help
I have following function which worked fine until i tried to call another assync request from this assync function. If i tried it secondary assync function always returns exception.
"Has bo method 'then'"
Has anybody idea what can causing it and how can i solve it plese?
Thanks for any help.
First assync function
$scope.getData = function() {
var deferred = $q.defer();
var DATE_FROM = dateFrom;
var DATE_TO = dateTo;
// INSTANTIATE DB CONNECTION
db = window.sqlitePlugin.openDatabase({name:"callplanner"});
var numberOfProcessed = 0;
for(var ic=0; ic < dateRanges.length; ic++) {
var sqlQuery =
"SELECT '"+dateRanges[ic].DATE_FROM+"' as DATE_FROM, "+
" '"+dateRanges[ic].DATE_TO+"' as DATE_TO, "+
" COUNT(*) AS DIALS_CNT, "+
" SUM(CASE WHEN dc.call_result = '"+CALL_RESULT_STATE_APPT+"' THEN 1 ELSE 0 END) AS '"+APPT_CNT+"', "+
" SUM(CASE WHEN dc.call_result = '"+CALL_RESULT_STATE_CONV_NO_APPT+"' THEN 1 ELSE 0 END) AS '"+CONVERS_CNT+"' , "+
" SUM(CASE WHEN dc.call_result = '"+CALL_RESULT_STATE_CANNOT_REACH+"' THEN 1 ELSE 0 END) AS '"+CANNOT_REACH_CNT+"' "+
" FROM "+DIALED_CALLS_TABLE+" dc "+
" WHERE dc.date BETWEEN '"+dateRanges[ic].DATE_FROM+"' AND '"+dateRanges[ic].DATE_TO+"';";
// PRINT QUERY
console.log(sqlQuery);
// PUSH QUERY TO ARRAY
sqlQueries.push(sqlQuery);
// PROCESS TRANSACTION
db.transaction(function(tx) {
// init empty array for results
tx.executeSql(sqlQueries[numberOfProcessed], [], function(tx,results){
for (var i=0; i < results.rows.length; i++){
//process your result from sql
numberOfProcessed++;
row = results.rows.item(i);
// Replace null values
if(row.APPT_CNT == null)
row.APPT_CNT = 0;
if(row.CONVERS_CNT == null)
row.CONVERS_CNT = 0;
if(row.CANNOT_REACH_CNT == null)
row.CANNOT_REACH_CNT = 0;
// End of replacing null values
row.YOUR_GOAL = $rootScope.goalValue;
row.YOUR_DEFICIT = DialsComputeService.computeDailyDeficit(row);
row.SUCCESS_RATE = DialsComputeService.computeSuccessRateDaily(row);
//row.SUCCESS_RATE_SINCE = DialsComputeService.computeSuccessRateSinceStart(row);
// GET DATA IN ASSYNC TASK
DialsComputeService.computeSuccessRateSinceStart.then(function(result){
// THIS GIVES THE VALUE:
//alert("Result is" + JSON.stringify(result));
console.log("Returned Result is: " + JSON.stringify(result));
try{
row.SUCCESS_RATE_SINCE = result;
} catch (e) {
$ionicLoading.show({
template: $translate.instant('ERROR'),
duration:1000
});
}
}, function(e){
$ionicLoading.show({
template: $translate.instant('ERROR_DATABASE'),
duration:1000
});
});
// END GET DATA IN ASSYNC TASK
statsData.push(row);
console.log("Result row is: " + JSON.stringify(row));
if(numberOfProcessed == dateRanges.length){
deferred.resolve(statsData); // resolve your promise when you are sure you handled everything
}
}
});
},function (e) {
alert("ERROR: " + e.message);
deferred.reject(e);
});
}
return deferred.promise;
};
Second assync function in service:
computeSuccessRateSinceStart: function(row) {
var deferred = $q.defer();
console.log("Trying to compute daily success rate since until" +row.DATE_TO);
var sqlQuery =
"SELECT " +
"("+
"SELECT COUNT(*) "+
"FROM dialed_calls AS dc "+
"WHERE dc.date < '"+row.DATE_TO+"'" +
") " +
"AS DIALS_CNT ," +
"("+
"SELECT COUNT(dc.call_result) "+
"FROM dialed_calls AS dc "+
"WHERE dc.call_result = 'APPT_CNT' "+
"AND "+
"dc.date < '"+row.DATE_TO+"'" +
") " +
"AS APPT_CNT ;";
console.log(sqlQuery);
db = window.sqlitePlugin.openDatabase({name:"callplanner"});
// GET APPT COUNT
db.transaction(function(tx) {
tx.executeSql(sqlQuery, [], function(tx,results){
// init empty array for results
for (var i=0; i < results.rows.length; i++){
row = results.rows.item(i);
//Udpate date for writeout
//row.DATE = moment(row.DATE).format('ddd DD.M');
console.log("row APPT count is " + JSON.stringify(row));
alert(JSON.stringify(row));
var successRateFromSince;
successRateFromSince = row.APPT_CNT / row.DIALS_CNT * (100);
successRateFromSince = Math.round(successRateFromSince);
if(isNaN(successRateFromSince)) {
successRateFromSince = 0;
}
console.log("Success rate since is " +successRateFromSince);
}
deferred.resolve(successRateFromSince);
});
},function (e) {
alert("ERROR: " + e.message);
$ionicLoading.show({
template: $translate.instant('ERROR_DATABASE'),
duration:1000
});
});
return deferred.promise;
}
};
Place where error is occured:
// GET DATA IN ASSYNC TASK
DialsComputeService.computeSuccessRateSinceStart.then(function(result){
// THIS GIVES THE VALUE:
//alert("Result is" + JSON.stringify(result));
console.log("Returned Result is: " + JSON.stringify(result));
try{
row.SUCCESS_RATE_SINCE = result;
} catch (e) {
$ionicLoading.show({
template: $translate.instant('ERROR'),
duration:1000
});
}
}, function(e){
$ionicLoading.show({
template: $translate.instant('ERROR_DATABASE'),
duration:1000
});
});
// END GET DATA IN ASSYNC TASK
Your async function computeSuccessRateSinceStart is a function, so you need to call it as a function and pass it a row as a parameter:
DialsComputeService.computeSuccessRateSinceStart(yourRow).then( ... )
Once you do that, the return value from the function will be a promise, which has a then() method.
What I'm trying to do:
Update the status to "TAKEN" when the chat is closed.
Issue:
Can't get $scope.currentChat.$set() or $scope.currentChat.$update() to work when trying to update the status. (See the $scope.close() function.)
What I've tried:
Various methods including $set, $update; I don't know. A lot of things. Been researching this for several hours, and can't find a solution that works.
NOTES:
$scope.currentChat.$set({status:"TAKEN"}); Doesn't work.
$scope.currentChat.$getRecord('status'); Works. Returns:
Object {$value: "OPEN", $id: "status", $priority: null}
So what exactly is going on here? Why can't I seem to set the status to TAKEN?
The issue is currently in the $scope.close() function, when trying to update the status:
// $SCOPE.CLOSE
// - Closes the current ticket.
$scope.close = function() {
// $scope.ticketObject.status = "TAKEN";
// $scope.currentChat.$set({status:"TAKEN"});
console.log("===========================");
console.log("STATUS:");
console.log($scope.currentChat.$getRecord('status'));
console.log($scope.currentChat['status']);
console.log("===========================");
$scope.ticketObject = {};
$scope.ticket = false;
$scope.toggle();
}
Here's my code:
bloop.controller('HomeCtrl', ['$scope', '$firebase', function($scope, $firebase) {
console.log("HomeController!");
var url = 'https://**********.firebaseio.com/tickets/';
var ref = new Firebase(url);
// $SCOPE.CREATETICKET
// - This function makes a connection to Firebase and creates the ticket.
$scope.createTicket = function() {
$scope.tickets = $firebase(ref).$asArray();
$scope.tickets.$add($scope.ticketObject).then(function(r) {
var id = r.name();
$scope.currentFBID = id;
$scope.syncTickets();
console.log("===========================");
console.log("CREATED TICKET: " + $scope.currentFBID);
console.log("URL: " + url + $scope.currentFBID);
console.log("===========================");
});
}
// $SCOPE.SYNCTICKETS
// - This function makes a connection to Firebase and syncs the ticket with the $scope to easily update the tickets.
$scope.syncTickets = function() {
var ticketRefURL = new Firebase(url + $scope.currentFBID);
$scope.currentChat = $firebase(ticketRefURL).$asArray();
$scope.currentChat.$save($scope.ticketObject);
var archiveRefURL = new Firebase(url + $scope.currentFBID + "/archive");
$scope.currentChat.archive = $firebase(archiveRefURL).$asArray();
console.log("===========================");
console.log("SAVED TICKET: " + $scope.currentFBID);
console.log("URL: " + ticketRefURL);
console.log("ARCHIVE URL: " + archiveRefURL);
console.log("===========================");
}
// $SCOPE.POST
// - This function pushes whatever is typed into the chat into the chat archive.
// - $scope.ticketObject.archive (is an array of objects)
$scope.post = function(name) {
// Push to ticketObject.archive array...
$scope.ticketObject.archive.push({
"name" : name,
"text" : $scope.chatText
});
// Logging the array to make sure it exists...
console.log("===========================");
console.log("CHAT ARCHIVE:");
console.log($scope.ticketObject.archive);
console.log("===========================");
$scope.currentChat.archive.$add({
"name" : name,
"text" : $scope.chatText
});
// This resets the text area so it's empty...
$scope.chatText = "";
} // WORKS
// $SCOPE.CLOSE
// - Closes the current ticket.
$scope.close = function() {
// $scope.ticketObject.status = "TAKEN";
// $scope.currentChat.$set({status:"TAKEN"});
console.log("===========================");
console.log("STATUS:");
console.log($scope.currentChat.$getRecord('status'));
console.log($scope.currentChat['status']);
console.log("===========================");
$scope.ticketObject = {};
$scope.ticket = false;
$scope.toggle();
}
// $SCOPE.TOGGLE
// - This function toggles the chat to be either open or closed.
$scope.toggle = function() {
if($scope.toggleState === false) {
$scope.toggleState = true;
$scope.checkTicket();
} else if($scope.toggleState === true) {
$scope.toggleState = false;
}
}
// $SCOPE.CHECKTICKET
// - This function checks to see if there's an existing ticket.
// - If there's not an existing ticket, it creates one.
$scope.checkTicket = function() {
if($scope.ticket === false) {
// Generate New Ticket Data
$scope.ticketObject = newTicket();
// Create the Ticket
$scope.createTicket();
// Ticket now exists.
$scope.ticket = true;
}
}
function newTicket() {
var ticketID = generateTicketID();
var newTicket = {
id: ticketID,
status: "OPEN",
name: "N/A",
email: "N/A",
date: generateDate(),
opID: "Unassigned",
opName: "Unassigned",
archive: [],
notes: []
}
return newTicket;
}
function generateTicketID() {
var chars = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ";
var result = '';
for(var i=12; i>0; --i) {
result += chars[Math.round(Math.random() * (chars.length - 1))];
}
return result;
}
function generateDate() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
if(dd < 10) {
dd = '0' + dd;
}
if(mm < 10) {
dd = '0' + mm;
}
var date = mm + "/" + dd + "/" + yyyy;
return date;
}
}]);
$update and $set are part of the $firebase API. You are attempting to call them on the synchronized array returned by $asArray(), which is a $FirebaseArray instance. That has its own API, which includes neither update nor set.