Using Angular XEditable inside UI-Router Partial - javascript

Can't get my form to work inside UI-Router, it works outside of the partial but not inside. XEditable is not "loading" it's like it's out of scope.
I tried to lazy load it using ocLazyLoadProvider but couldn't get that to work either.
Please help!
my code:
Main view:
doctype html
html(lang="en")
include ../includes/head
body.backoffice
div.container
include ../includes/navbar
.page-body(ng-app='geckoAdminApp')
include includes/nav
div(ui-view='maincontent')
//include includes/management
div.padding
include ../includes/foot
Partial View:
//-
//- Buildings Form
//-
div(ng-controller='BuildingsController')
h2 Edificios
table.table.table-bordered.table-hover.table-condensed.table-striped
thead.thead-default
tr
th
strong Nome
th
strong Descrição
th
strong Total de Espaços
th
strong Total de Boxes
th
tr(ng-repeat='building in buildingsData')
td
a( ng-click='setCurrentBuildingID(building.idBuilding, building.shortName)' ng-show='toggleShortname' href='') {{ building.shortName }}
span( ng-hide='toggleShortname' editable-text='building.shortName' e-name='shortName' e-form='buildingrowform') {{ building.shortName }}
td
span(editable-text='building.description' e-name='description' e-form='buildingrowform') {{ building.description }}
td
span(editable-number='building.nSpaces' e-name='nSpaces' e-form='buildingrowform') {{ building.nSpaces }}
td
span(editable-number='building.nBoxes' e-name='nBoxes' e-form='buildingrowform') {{ building.nBoxes }}
td(style='white-space: nowrap')
// form
form(editable-form myForm name='buildingrowform' onbeforesave='saveBuildingData($data, building.idBuilding)' ng-show='buildingrowform.$visible' class='form-buttons form-inline' shown='inserted == building')
button.glyphicon.glyphicon-save.glyphButton.btn-to-glyph.glyphButtonOk(type='submit' title='Salvar' ng-disabled='buildingrowform.$waiting')
a(href='' ng-disabled='buildingrowform.$waiting' ng-click='buildingrowform.$cancel()' title='Cancelar')
span.glyphicon.glyphicon-remove-circle.glyphButton.glyphButtonAlert(aria-hidden='true')
div.buttons(ng-show='!buildingrowform.$visible')
a(href='' ng-click='buildingrowform.$show(); toggleShortnameFunction()' title="Editar")
span.glyphicon.glyphicon-edit.glyphButton(aria-hidden='true')
a(href='' ng-click='removeBuilding(building.idBuilding, $index)' title="Remover")
span.glyphicon.glyphicon-remove.glyphButton.glyphButtonAlert(aria-hidden='true')
a(href='' ng-click='addBuildingRow()' title="Adicionar")
span.glyphicon.glyphicon-plus.glyphButton.glyphButtonOk(aria-hidden='true')
Angular:
angular.module('geckoAdminApp', ['xeditable', 'ui.router'])
.config(function($stateProvider, $urlRouterProvider){
$stateProvider
.state('edificios', {
url: '/edificios',
views: {
'maincontent': { templateUrl: '/partials/admin/partial-buildings.html' }
},
controller: 'BuildingsController'//,
});
})
.controller('BuildingsController', ['$scope', '$filter', '$http', '$window', function ($scope, $filter, $http, $window) {
// $ocLazyLoad.load('xeditable');
$scope.buildingsData = [];
$scope.regex = /[A-Z]{1}\d{2}$/;
$scope.currentBuildingID = '';
$scope.setCurrentBuildingID = function (id, shortName) {
console.log('>> ID: ' + id);
$scope.currentBuildingID = id;
$window.location.href = '/admin/edificio/' + shortName;
};
$scope.toggleShortnameFunction = function () {
$scope.toggleShortname = !$scope.toggleShortname;
};
$scope.GetBuildings = function () {
$http.get(GeckoBuildingUrl).then(function (res) {// jshint ignore:line
$scope.buildingsData = res.data.item; //TODO: Verificar status code
console.log(res.data);
}, function (res) {
console.log('ERROR: Can\'t get buildings: ' + res.data);
$scope.buildingsData = [];
});
};
$scope.GetBuildings();
$scope.saveBuildingData = function (building, buildingId) {
if (buildingId) {
$scope.toggleShortnameFunction();
console.log('Update Building: ' + building.shortName + ' ' + building.description + ' ' + building.nSpaces + ' ' + building.nBoxes + ' ');
$http({
url: GeckoBuildingUrl + '/' + buildingId,// jshint ignore:line
//url: building.URI,
method: 'PUT',
contentType: 'application/x-www-form-urlencoded',
data: {
shortName: building.shortName,
description: building.description,
nSpaces: String(building.nSpaces),
nBoxes: String(building.nBoxes)
}
}).then(function successCallback() {
$scope.GetBuildings();
}, function errorCallback(response) {
console.log(response);
});
} else {
console.log('New Building: ' + building.shortName + ' ' + building.description + ' ' + building.nSpaces + ' ' + building.nBoxes + ' ');
$http({
url: GeckoBuildingUrl,// jshint ignore:line
method: 'POST',
contentType: 'application/x-www-form-urlencoded',
data: {
shortName: building.shortName,
description: building.description,
nSpaces: String(building.nSpaces),
nBoxes: String(building.nBoxes)
}
}).then(function successCallback(response) {
$scope.GetBuildings();
console.log('success post:' + response);
}, function errorCallback(response) {
console.log(response);
});
}
};
$scope.removeBuilding = function (buildingId, index) {
if (buildingId) {
console.log(GeckoBuildingUrl + '/' + buildingId);// jshint ignore:line
$http({
url: GeckoBuildingUrl + '/' + buildingId,// jshint ignore:line
method: 'DELETE',
contentType: 'form-data',
data: {}
}).then(function successCallback(response) {
$scope.GetBuildings();
console.log('success DELETE:' + response);
}, function errorCallback(response) {
console.log('error DELETE:' + response);
});
}
$scope.buildingsData.splice(index);
};
$scope.addBuildingRow = function () {
$scope.inserted = {
shortName: '',
description: '',
nSpaces: 0,
nBoxes: 0
};
$scope.buildingsData.push($scope.inserted);
};
}]);
Thanks!

Related

Javascript Ajax call returns same string multiple times from XML. How can this be avoided?

I have the following issue: When I make an Ajax call to give people an option to "autofill" a field, it offers the same string (as seen in the image below). The problem is, that the Ajax call uses an URL where the string appears in an XML multiple times.
For example, when calling
/tools/_api/web/lists/getbytitle('Besucheranmeldung')/Items?&$filter=substringof('Aalen', FirmaNeu)&$select=FirmaNeu
the XML will look something like that:
<?xml version="1.0" encoding="utf-8"?><feed xml:base="https://mylink/tools/_api/" xmlns="http://www.w3.org/2005/Atom" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns:georss="http://www.georss.org/georss" xmlns:gml="http://www.opengis.net/gml"><id>fbe3c761-2113-4be6-b8dd-599cf842df2f</id><title /><updated>2020-12-16T12:58:45Z</updated><entry m:etag=""2""><id>Web/Lists(guid'5d3a8bf8-7edf-4b7e-aab8-5df6cd818573')/Items(10891)</id><category term="SP.Data.BesucheranmeldungListItem" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" /><link rel="edit" href="Web/Lists(guid'5d3a8bf8-7edf-4b7e-aab8-5df6cd818573')/Items(10891)" /><title /><updated>2020-12-16T12:58:45Z</updated><author><name /></author><content type="application/xml"><m:properties><d:FirmaNeu>IGM Aalen</d:FirmaNeu></m:properties></content></entry><entry m:etag=""2""><id>Web/Lists(guid'5d3a8bf8-7edf-4b7e-aab8-5df6cd818573')/Items(10893)</id><category term="SP.Data.BesucheranmeldungListItem" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" /><link rel="edit" href="Web/Lists(guid'5d3a8bf8-7edf-4b7e-aab8-5df6cd818573')/Items(10893)" /><title /><updated>2020-12-16T12:58:45Z</updated><author><name /></author><content type="application/xml"><m:properties><d:FirmaNeu>'IGM Aalen</d:FirmaNeu></m:properties></content></entry><entry m:etag=""2""><id>Web/Lists(guid'5d3a8bf8-7edf-4b7e-aab8-5df6cd818573')/Items(10894)</id><category term="SP.Data.BesucheranmeldungListItem" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" /><link rel="edit" href="Web/Lists(guid'5d3a8bf8-7edf-4b7e-aab8-5df6cd818573')/Items(10894)" /><title /><updated>2020-12-16T12:58:45Z</updated><author><name /></author><content type="application/xml"><m:properties><d:FirmaNeu>IGM Aalen</d:FirmaNeu></m:properties></content></entry><entry m:etag=""2""><id>Web/Lists(guid'5d3a8bf8-7edf-4b7e-aab8-5df6cd818573')/Items(10895)</id><category term="SP.Data.BesucheranmeldungListItem"
I use the following code to get the dropdown:
var requestHeaders = {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": NWF$("#__REQUESTDIGEST").val()
};
function startAutoComplete(varTextBoxId, listname) {
console.log("startAutoComplete called!");
NWF$("#" + varTextBoxId).autocomplete({
source: function (request, response) {
var query = getQuery(request.term, listname);
var testurl = "/tools/_api/web/lists/getbytitle('" + listname + "')/Items?&$filter=" + query;
console.log("testurl: " + testurl);
NWF$.ajax({
url: "/tools/_api/web/lists/getbytitle('" + listname + "')/Items?&$filter=" + query,
contentType: "application/json;odata=verbose",
headers: requestHeaders,
error: function (xhr, ajaxOptions, thrownError) {
alert("error:" + thrownError + "\n" + xhr.status);
},
success: function (data) {
response(NWF$.map(data.d.results, function (item) {
switch (listname) {
case "Besucheranmeldung":
return {
label: item.FirmaNeu,
value: item.FirmaNeu,
id: item.FirmaNeu,
listname: listname
}
break;
}
}));
}
});
},
minLength: 2,
select: function (event, ui) {
},
open: function () {
NWF$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
NWF$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
}
function getQuery(requestStr, listname) {
var retvalue = "";
requestStr = encodeURIComponent(requestStr);
switch (listname) {
case "Besucheranmeldung":
retvalue = "substringof('" + requestStr + "', FirmaNeu)" + "&$select=FirmaNeu";
break;
}
// console.log("retvalue: " + retvalue);
return retvalue;
}
How can this be avoided? Is there a way to make an if statement which checks whether the dropdown contains the same string twice to avoid letting it appear there multiple times?
When I do console.log(data.d.results);, I get the following:
Fixed it by changing the code:
var requestHeaders = {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": NWF$("#__REQUESTDIGEST").val()
};
function startAutoComplete(varTextBoxId, listname) {
console.log("startAutoComplete called!");
NWF$("#" + varTextBoxId).autocomplete({
source: function (request, response) {
var query = getQuery(request.term, listname);
NWF$.ajax({
url: "/tools/_api/web/lists/getbytitle('" + listname + "')/Items?&$filter=" + query,
contentType: "application/json;odata=verbose",
headers: requestHeaders,
error: function (xhr, ajaxOptions, thrownError) {
alert("error:" + thrownError + "\n" + xhr.status);
},
success: function (data) {
// console.log(data.d.results);
var firmaResults;
var firmen = [];
firmaResults = groupBy(data.d.results,'FirmaNeu');
// console.log(firmaResults);
for (var i = 0; i < firmaResults.length; i++ ){
firmen[i] = firmaResults[i];
}
var counter = -1;
response(NWF$.map(data.d.results, function (item) {
switch (listname) {
case "Besucheranmeldung":
counter++;
if (counter > firmaResults.length){
return;
}
return {
label: firmen[counter],
value: firmen[counter],
id: firmen[counter],
listname: listname
}
break;
}
}));
}
});
},
minLength: 2,
select: function (event, ui) {
},
open: function () {
NWF$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
NWF$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
}
function getQuery(requestStr, listname) {
var retvalue = "";
requestStr = encodeURIComponent(requestStr);
switch (listname) {
case "Besucheranmeldung":
retvalue = "substringof('" + requestStr + "', FirmaNeu)" + "&$select=FirmaNeu";
break;
}
// console.log("retvalue: " + retvalue);
return retvalue;
}
function groupBy(items,propertyName)
{
var result = [];
$.each(items, function(index, item) {
if ($.inArray(item[propertyName], result) == -1) {
result.push(item[propertyName]);
}
});
return result;
}

Angular display a single record from json

I've just started getting into using Angular and having an issue displaying a single record that is being returned from using $http (get). I'm getting the data back correctly. This is the html I've got....
<div ng-controller="UserDataController as udCtrl">
Name: {{udCtrl.user.name}}
</div>
<div id="debug" style="margin-top:24px;border:solid 1px #900;background:#efefef;min-height:100px"></div>
have also tried and a couple of other variations...
Name: {{udCtrl.name}}
Javascript:
(function() {
var app = angular.module('rtcTimesheet', []);
var servicePath="/angular/";
$("#debug").append("Starting...<br/>");
app.controller("UserDataController",["$http",function($http){
var user=this;
user=[];
$http({
method: 'GET',
url: servicePath+'login.php',
params: {
un: "username",
pwd: "123456789"
}
}).then(function(response){
if(response.data.hasOwnProperty("HasError")) {
$("#debug").append("ERROR: " + response.data.ErrorMessage);
} else {
$("#debug").append("Data: " + JSON.stringify(response.data));
user=response.data;
}
},function (err){
alert("ERROR: "+err.status); //data, status, headers, config, statusText
});
}]);
app.controller("UserTest",function(){
this.user=users;
});
var users = {
id: '1',
name: 'Joe Bloggs'
};
})();
This is what is returned in JSON format and I can see this in the little debug area I created.
{"data":{"id":"1","name":"Joe Bloggs"}
if I change the html to use the code below it works.
<div ng-controller="UserTest as udCtrl">
Name: {{udCtrl.user.name}}
</div>
I just cannot see where I'm going wrong and why it will not display the returned name.
Define the user variable on $scope and access it with $scope.user. You are having referance problem.
Example
//Define user variable like this.
$scope.user = {};
//On response -->
}).then(function(response){
if(response.data.hasOwnProperty("HasError")) {
$("#debug").append("ERROR: " + response.data.ErrorMessage);
} else {
$("#debug").append("Data: " + JSON.stringify(response.data));
$scope.user=response.data;
}
}
EDIT
If you want to use udCtrl referance define variable under thisvariable on controller.
//Define user variable like this.
var ctrl = this;
ctrl.user = {};
//On response -->
}).then(function(response){
if(response.data.hasOwnProperty("HasError")) {
$("#debug").append("ERROR: " + response.data.ErrorMessage);
} else {
$("#debug").append("Data: " + JSON.stringify(response.data));
ctrl.user=response.data;
}
}
EDIT 2 FOR ABSOLUTE ANSWER
(function() {
var app = angular.module('rtcTimesheet', []);
var servicePath="/angular/";
$("#debug").append("Starting...<br/>");
app.controller("UserDataController",["$http",function($http){
var udCtrl=this;
udCtrl.user=[];
$http({
method: 'GET',
url: servicePath+'login.php',
params: {
un: "username",
pwd: "123456789"
}
}).then(function(response){
if(response.data.hasOwnProperty("HasError")) {
$("#debug").append("ERROR: " + response.data.ErrorMessage);
} else {
$("#debug").append("Data: " + JSON.stringify(response.data));
udCtrl.user=response.data;
}
},function (err){
alert("ERROR: "+err.status); //data, status, headers, config, statusText
});
}]);
app.controller("UserTest",function(){
this.user=users;
});
var users = {
id: '1',
name: 'Joe Bloggs'
};
})();

Http request configuration url must be a string. Received: undefined

I just moved my upload function from controller (where it was working as it should) to factory and it sudenly stopped working. I'm keep getting this error, but i don't know/understand where the problem is
angular.js:13550 Error: [$http:badreq] Http request configuration url must be a string. Received: undefined
http://errors.angularjs.org/1.5.5/$http/badreq?p0=undefined
at angular.js:68
at $http (angular.js:11194)
at uploadWithAngular (ng-file-upload.js:91)
at sendHttp (ng-file-upload.js:144)
at upload (ng-file-upload.js:330)
at Scope.$scope.uploadDocument (locationsCtrl.js:131)
at fn (eval at compile (angular.js:14432), <anonymous>:4:338)
at expensiveCheckFn (angular.js:15485)
at callback (angular.js:25018)
at Scope.$eval (angular.js:17229)
This is my upload document function in controller
$scope.uploadDocument = function(file) {
if($scope.documentName.length > 4) {
$scope.errorMsg = '';
file.upload = Upload.upload( documentsFactory.uploadDocument(
$scope.id_location,
$scope.documentName,
$scope.documentDescription,
file,
$scope.locationUniqueId
));
file.upload.then(function (response) {
$scope.documentName = $scope.documentDescription = $scope.userFile = '';
documentsFactory.getDocuments($scope.id_location).then(function (data) {
$scope.documents = data;
});
$timeout(function () {
file.result = response.data;
});
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
}, function (evt) {
// Math.min is to fix IE which reports 200% sometimes
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
}else{
$scope.errorMsg = 'Name should be at least 5 chars long';
}
};
And this is my factory
factory.uploadDocument = function(id_location, name, description, file, locationUniqueId){
return $http({
method: 'POST',
url: $location.protocol() + '://' + $location.host() + '/rest/api/document/documents',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: {
id_location: id_location,
name: name,
description: description,
userFile: file,
locationUniqueId: locationUniqueId
}
}).then(function successCallback(response){
return response.data;
},function errorCallback(response){
console.log('Error uploading documents: ' + response);
});
};
UPDATE:
This is working example if i make "upload request" in my controller
file.upload = Upload.upload({
url: $location.protocol() + '://' + $location.host() + '/rest/api/document/documents/',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: {
id_location: $scope.id_location,
name: $scope.documentName,
description: $scope.documentDescription,
userFile: file,
locationUniqueId: $scope.locationUniqueId
}
});
If you need any additional inflammations please let me know and i will provide. Thank you in advance
Following the error stack:
From ng-file-upload repository.
this.upload = function (config, internal) {
which is called by you there
Upload.upload( documentsFactory.uploadDocument(
$scope.id_location,
$scope.documentName,
$scope.documentDescription,
file,
$scope.locationUniqueId
));
line 330
return sendHttp(config);
line 144
uploadWithAngular();
line 91
$http(config).then(function (r) {
Where the error gets thrown. It looks like Upload.upload doesn't accept a promise, but a config for the $http call.
EDIT
What about returning the config object?
factory.uploadDocument = function(id_location, name, description, file, locationUniqueId){
return {
method: 'POST',
url: $location.protocol() + '://' + $location.host() + '/rest/api/document/documents',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: {
id_location: id_location,
name: name,
description: description,
userFile: file,
locationUniqueId: locationUniqueId
}
}
};
The best idea would be to move Upload to the factory and return the promise.
factory.uploadDocument = function(id_location, name, description, file, locationUniqueId){
return Upload.upload({
method: 'POST',
url: $location.protocol() + '://' + $location.host() + '/rest/api/document/documents',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: {
id_location: id_location,
name: name,
description: description,
userFile: file,
locationUniqueId: locationUniqueId
}
});

Angular Contact form email submission issue

I have created a contact Click here for example i believe i have created all the credentials needed for this form, however when i sent the message to the email credentials highlighted in my code, i don't an email submission from the sender. Does anyone know how this problem can be solved ?
angular
.module('hfApp')
.controller('contactCtrl', ['$scope','$http', function($scope, $http) {
$scope.success = false;
$scope.error = false;
$scope.send = function () {
var htmlBody ='<div>Name: ' + $scope.user.name + '</div>' +
'<div>Email: ' + $scope.user.email + '</div>' +
'<div>Message: ' + $scope.user.body + '</div>' +
'<div>Date: ' + (new Date()).toString() + '</div>';
$http({
url: 'http://www.hfpersonaltrainer.com/',
method: 'POST',
data: {
'From': 'foo#foo.com',
'To': 'nate.tyrone#gmail.com',
'HtmlBody': htmlBody,
'Subject': 'New Contact Form Submission'
},
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-Postmark-Server-Token': '8569dcd45-6a1a-4e7b-ae75-ea37629de4'
}
}).
success(function (data) {
$scope.success = true;
$scope.user = {};
}).
error(function (data) {
$scope.error = true;
});
};
}])

Angular JS contact form

I'm trying to come to grips with created an angularjs Contact form. Below is a link of what I have created thus far. Click Here I fill I am on the write track with the code i have written
var app = angular.module("myApp", []);
app.controller("contactCtrl", function ($scope) {
$scope.success = false;
$scope.error = false;
$scope.send = function () {
var htmlBody ='<div>Name: ' + $scope.user.name + '</div>' +
'<div>Email: ' + $scope.user.email + '</div>' +
'<div>Message: ' + $scope.user.body + '</div>' +
'<div>Date: ' + (new Date()).toString() + '</div>';
$http({
url: 'https://api.postmarkapp.com/email',
method: 'POST',
data: {
'From': 'foo#foo.com',
'To': 'me#gmail.com',
'HtmlBody': htmlBody,
'Subject': 'New Contact Form Submission'
},
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-Postmark-Server-Token': '8569dcd45-6a1a-4e7b-ae75-ea37629de4'
}
}).
success(function (data) {
$scope.success = true;
$scope.user = {};
}).
error(function (data) {
$scope.error = true;
});
}
});
However I am receiving two errors
And also
{"error": "Please use POST request"}
Does anyone know how I can solve this issues, I've wasted too many hours trying to get my head around it?
You don't declare the $http. It should be:
app.controller("contactCtrl", ['$scope','$http',function ($scope,$http){
// your code
}]);

Categories

Resources