I have a menu that I walk with a "ng-repeat" to paint the problem that I have is that if you burn a variable with the json from the menu that is painted correctly, but if the menu as consumption from a WebAPI not paint me complete, menu is as if first paint the html consultation before the end of the WebAPI.
The menu paints me correctly, but a submenu (dropdown) does not paint me children.
They know how to solve it?
This is the menu
This is the html
<div ng-controller="dashboardController" class="nav-wrapper">
<ul ng-init="menuApp()">
<li ng-repeat="item in menus" ng-init="$last && rebindDropDowns()" class="{{item.Submenu.length ? 'dropdown-button' : ''}}" ng-bind-html="item.Nombre" data-activates="{{item.Submenu.length ? 'administracion' : ''}}">
{{item.Opcion}}
<ul ng-if="item.Submenu.length>0" id="administracion" class="dropdown-content">
<li ng-repeat="subItem in item.Submenu"><a ng-href="{{subItem.Nombre}}">{{subItem.Descripcion}}</a></li>
</ul>
</li>
</ul>
</div>
And this is the Controller
(function() {
'use strict';
angular.module('gastosDeViaje').controller('dashboardController', ['$scope', 'dashboardService', 'accesoService', 'notificaService', 'legalizacionService', '$location', '$q',
function($scope, dashboardService, accesoService, notificaService, legalizacionService, $location, $q, men) {
$scope.menuApp = function() {
accesoService.consultaMenu(accesoService.authentication.userName).then(function(result) {
$scope.menus = result.data;
console.log(result);
});
};
$scope.rebindDropDowns = function() {
console.log('entro drop');
$('.dropdown-button').dropdown();
};
$scope.menu = [{
"Opcion": "Solicitud",
"Nombre": "<i class=\"material-icons left\">flight</i>Solicitud ",
"Descripcion": "Formulario para Solicitud",
"Submenu": []
}, {
"Opcion": "Consultas",
"Nombre": "<i class=\"material-icons left\">search</i>Consultas ",
"Descripcion": "Formulario para Consultas",
"Submenu": []
}, {
"Opcion": "Transferencia",
"Nombre": "<i class=\"material-icons left\">attach_money</i>Transferencia ",
"Descripcion": "Transferencia",
"Submenu": []
}, {
"Opcion": "Administracion",
"Nombre": "<a class=\"dropdown-button\" data-activates=\"administracion\"><i class=\"material-icons left\">settings</i>Administracion<i class=\"material-icons right\">arrow_drop_down</i></a> ",
"Descripcion": "Menu de Administracion",
"Submenu": [{
"Opcion": "Reservas",
"Nombre": "#/reservas ",
"Descripcion": "Reservas",
"Submenu": null
}, {
"Opcion": "Globales",
"Nombre": "#/globales ",
"Descripcion": "Globales",
"Submenu": null
}, {
"Opcion": "Convenios",
"Nombre": "#/convenios ",
"Descripcion": "Convenios",
"Submenu": null
}, {
"Opcion": "Aplicacion",
"Nombre": "#/aplicacion ",
"Descripcion": "Aplicacion",
"Submenu": null
}]
}];
dashboardService.getEmpleadoAprobar(accesoService.authentication.userName).then(function(results) {
$scope.empleadosAprobar = results.data;
}, function() { //error
console.log('Error al Cargar los datos');
});
dashboardService.getEmpleadoAutorizar(accesoService.authentication.userName).then(function(results) {
$scope.empleadosAutorizar = results.data;
}, function() { //error
console.log('Error al cargar las autorizaciones');
});
dashboardService.getEmpleadolegalizar(accesoService.authentication.userName).then(function(results) {
$scope.empleadoLegalizar = results.data;
}, function() { //error
console.log('error al consultar');
});
dashboardService.getEmpleadoPdtLegalizarSub(accesoService.authentication.userName).then(function(results) {
$scope.PdtLegalizarSub = results.data;
}, function() {
console.log('Error al traer los pdtes por Legalizar');
});
dashboardService.getLegPdtAutorizar(accesoService.authentication.userName).then(function(result) {
$scope.LegPdtAutorizar = result.data;
}, function(error) {
console.log(error);
});
dashboardService.getLegPdtAprobar(accesoService.authentication.userName).then(function(result) {
$scope.LegPdtAprobar = result.data;
}, function(error) {
console.log(error);
});
dashboardService.getEmpleado(accesoService.authentication.userName).then(function(result) {
$scope.Nombre = result.data.Nombre;
}, function(error) {
if (!angular.isUndefined(error)) {
angular.forEach(error.data.ModelState.Model, function(errores) {
notificaService.error(errores);
});
}
});
dashboardService.solicitudesActivasEmpleado(accesoService.authentication.userName).then(function(result) {
$scope.solActivas = result.data;
});
/*$scope.solicitudesActivasEmpleado = function(){
console.log('entro activas');
$scope.pagActual = 0;
$scope.pageZise = 3;
$q.all([
dashboardService.solicitudesActivasEmpleado(accesoService.authentication.userName)
]).then(function(results){
$scope.solActivas = results[0].data;
$scope.numPaginas = function(){
return Math.ceil($scope.solActivas.length / $scope.pageZise);
};
}, function(error){
console.log(error);
});
};*/
$scope.CambiaEstadoSol = function(id, documento, estado) {
var parametros = '?id=' + id + '&documento=' + documento + '&estado=' + estado + '&funLog=' + accesoService.authentication.userName;
dashboardService.putCambiaEstadoSol(parametros).then(function() { //results
$location.path('#/dashboard'); //Lo hago para que me actualice la lista de pendientes x aprobar
if (estado === 'A') {
notificaService.success('Solicitud Aprobada Exitosamente');
}
if (estado === 'T') {
notificaService.success('Solicitud Autorizada Exitosamente');
/*if (documento==='L') {
//legalizacionService.postLegalizarAndres
}*/
}
if (estado === 'N') {
notificaService.success('Solicitud Anulada Exitosamente');
}
}, function(error) {
error.data.ModelState.Model.forEach(function(data) {
notificaService.error(data);
});
});
};
$scope.VerSolicitud = function(id) {
$location.path('/solicitud/' + id);
};
$scope.LegalizarSolicitud = function(id) {
$location.path('/legalizacion/' + id + '/' + 'L');
};
$scope.CambiaEstadoLeg = function(id) {
$location.path('/legalizacion/' + id + '/' + 'A');
};
}
]);
angular.module('gastosDeViaje').filter('paginacion', function() {
return function(input, start) {
if (!input || !input.length) {
return;
}
start = +start;
return input.slice(start);
};
});
})();
The problem seems to be on $('.dropdown-button').dropdown(); that is called from template in <li ng-repeat="item in menus" ng-init="$last && rebindDropDowns()"... but I can't simulate this issue.
It happens because ng-init is running before render html on DOM. Then when you apply jQuery plugin, the element doesn't exists yet.
By the way, using jQuery inside controller is not a good idea at all.
UPDATE 1
Try using a directive to initialize jQuery plugins like so:
angular.module('gastosDeViaje').directive('dropdownButton',
function() {
return {
restrict: 'EAC',
link: function($scope, element, attrs, controller) {
jQuery(element).dropdown();
}
};
}
);
This will apply directive for the class .dropdown-button.
I made this change and it worked: D
<div ng-controller="dashboardController" class="nav-wrapper">
<ul ng-init="menuApp()">
<li ng-repeat="item in menus" class="{{item.Submenu.length ? 'dropdown-button' : ''}}" ng-bind-html="item.Nombre" data-activates="{{item.Submenu.length ? 'administracion' : ''}}">
{{item.Opcion}}
<ul ng-if="item.Submenu.length>0" id="administracion" class="dropdown-content">
<li ng-repeat="subItem in item.Submenu" ng-init="$last && rebindDropDowns()">
<a ng-href="{{subItem.Nombre}}">{{subItem.Descripcion}}</a>
</li>
</ul></li></ul></div>
Related
I'm using the below JS to feed options for my select:
//**** Instance des Bootstrap-SelectPicker ****
$('.selectpicker').selectpicker({
style: 'btn-info',
size: 4,
showSubtext: true,
noneSelectedText: 'Pas de sélection',
showSubtext: true,
showTick: true,
});
var menus = [
{ controleur: "CatDdeurs", element: "Cat_Ddeur" },
{ controleur: "Communautes", element: "Communaute" },
{ controleur: "Occupations", element: "Occupation" },
{ controleur: "Provinces", element: "Province" },
{ controleur: "Scolarites", element: "Scolarite" },
{ controleur: "Sexes", element: "Sexe" },
{ controleur: "Situations_Matrimoniales", element: "SituationMatrimoniale" },
{ controleur: "Source_De_Revenus", element: "SrceRevenu" },
{ controleur: "Statuts_Legaux", element: "StatutLegal" },
{ controleur: "Tranche_Revenu", element: "TrancheRevenu" },
{ controleur: "Villes", element: "Ville" },
{ controleur: "Sources_Informations", element: "SceInfo" },
{ controleur: "Langues", element: "langMaternelle" },
{ controleur: "Langues", element: "LangAutre" },
{ controleur: "Conseillers", element: "Conseiller" },
];
menus.forEach(x => {
MenusDeroulants('GetListe' + x.controleur, $('#cbx_' + x.element));
});
//**** Permet de remplir la liste des menus déroulants ****
function MenusDeroulants(url, dropdown) {
$.getJSON(url, function (data) {
dropdown.empty();
for (var i = 0; i < data.length; i++) {
var obj = data[i];
for (var key in obj) {
var prenom;
var nom;
var ID;
//**** Traitement des demandeurs ou conseillers ****
if (url == "GetListeConseillers" || url == "GetListeDemandeurs") {
//**** Retrait du code ****
if (key == 'Code_Conseiller' || key == 'Code_Demandeur') {
ID = obj[key];
};
//**** Retrait du Nom ****
if (key == 'Nom_Conseiller' || key == 'Nom_Demandeur') {
//if (key.match(/Nom_C*/) || key.match(/Nom_D*/)) {
nom = obj[key];
};
//**** Retrait du Prénom ****
if (key == 'Prenoms_Conseiller' || key == 'Prenoms_Demandeur') {
prenom = obj[key];
};
} else { //**** Traitement des autres menus ****
//**** Retrait de l'ID ****
if (key.match(/ID_*/)) {//**** Traitement des demandeurs ou conseillers ****
ID = obj[key];
};
//**** Retrait du Nom ****
if (key.match(/Nom_*/)) {
nom = obj[key];
};
};
}
//**** On construit les options du menu déroulant ****
if (url == "GetListeConseillers" || url == "GetListeDemandeurs") {
dropdown.append($("<option></option>").attr("value", ID).text(nom).attr("data-subtext", prenom));
} else {
dropdown.append($("<option></option>").attr("value", ID).text(nom));
};
if ((nom.toUpperCase() == "CHICOUTIMI" && url == 'GetListeVilles')
|| (nom.toUpperCase() == "QUÉBEC" && url == 'GetListeProvinces')
|| (nom.toUpperCase() == "NON DISPONIBLE" && url != 'GetListeVilles' && url != 'GetListeProvinces')) {
dropdown.prop("selectedIndex", i);
};
}
dropdown.selectpicker('refresh');
});
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/css/bootstrap-select.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/js/bootstrap-select.min.js"></script>
<td style="padding-left:10px">
<div class="form-group">
<label for="cbx_Sexe" class="control-label">Sexe:</label>
<div>
<select class="selectpicker" id="cbx_Sexe"></select>
</div>
</div>
</td>
The first 12 elements will work fine but as soon as I add the 3 last, my selects will start behaving funny: The 3 lasts will sometimes work fine and some times show a white space on top of the box.
Sometimes, menus will not close when I open others... and so on.
I have tried combining the 12 first with each of the 3 lasts but there will always be something.
More strange is that if I use let say : "{ controleur: "Sexes", element: "Sexe" }," to fill all 3 that are giving me issue, all works perfectly.
Below is a screenshot of the display I'm getting:
Changing my function (MenusDeroulants) parameter dropdown to $dropdown finally solved the issue.
I really tried hard to refresh datatable with new data but couldn't achieve it. I initialize datatable with ng-repeat and get the data from api. Any idea would be perfect. Here is my html code:
<table class="table table-bordered table-striped table-hover js-dataTable-full dt-responsive" width="100%" id="dataTableId">
<thead>
<tr>
<th>NO</th>
<th>COMPANY CODE</th>
<th>CREATED DATE</th>
<th>DESCRIPTION</th>
<th>DUE DATE</th>
<th>CREATED BY</th>
<th>STATUS</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="document in documents" ng-if="document.status == 0 || document.status == 2">
<td>{{document.group_order_id}}</td>
<td>{{document.company.code}}</td>
<td>{{document.created}}</td>
<td>{{document.description}}</td>
<td>{{document.due_date}}</td>
<td>{{document.created_by_user.first_name}} {{document.created_by_user.last_name}}</td>
<td><span>Status</span></td>
</tr>
</tbody>
</table>
And here is my controller:
// Init full DataTable, for more examples you can check out https://www.datatables.net/
var initDataTableFull = function () {
if (!$.fn.dataTable.isDataTable('.js-dataTable-full')) {
jQuery('.js-dataTable-full').dataTable({
"language": {
"sProcessing": "İşleniyor...",
"sLengthMenu": "Sayfada _MENU_ Kayıt Göster",
"sZeroRecords": "Eşleşen Kayıt Bulunmadı",
"sInfo": " _TOTAL_ Kayıttan _START_ - _END_ Arası Kayıtlar",
"sInfoEmpty": "Kayıt Yok",
"sInfoFiltered": "( _MAX_ Kayıt İçerisinden Bulunan)",
"sInfoPostFix": "",
"sSearch": "Bul:",
"sUrl": "",
"oPaginate": {
"sFirst": "İlk",
"sPrevious": "Önceki",
"sNext": "Sonraki",
"sLast": "Son"
}
},
"order" : [[0, "desc"]]
});
}
};
// DataTables Bootstrap integration
var bsDataTables = function () {
var DataTable = jQuery.fn.dataTable;
// Set the defaults for DataTables init
jQuery.extend(true, DataTable.defaults, {
dom: "<'row'<'col-sm-6'l><'col-sm-6'f>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-6'i><'col-sm-6'p>>",
renderer: 'bootstrap',
oLanguage: {
sLengthMenu: "_MENU_",
sInfo: "Showing <strong>_START_</strong>-<strong>_END_</strong> of <strong>_TOTAL_</strong>",
oPaginate: {
sPrevious: '<i class="fa fa-angle-left"></i>',
sNext: '<i class="fa fa-angle-right"></i>'
}
}
});
// Default class modification
jQuery.extend(DataTable.ext.classes, {
sWrapper: "dataTables_wrapper form-inline dt-bootstrap",
sFilterInput: "form-control",
sLengthSelect: "form-control"
});
// Bootstrap paging button renderer
DataTable.ext.renderer.pageButton.bootstrap = function (settings, host, idx, buttons, page, pages) {
var api = new DataTable.Api(settings);
var classes = settings.oClasses;
var lang = settings.oLanguage.oPaginate;
var btnDisplay, btnClass;
var attach = function (container, buttons) {
var i, ien, node, button;
var clickHandler = function (e) {
e.preventDefault();
if (!jQuery(e.currentTarget).hasClass('disabled')) {
api.page(e.data.action).draw(false);
}
};
for (i = 0, ien = buttons.length; i < ien; i++) {
button = buttons[i];
if (jQuery.isArray(button)) {
attach(container, button);
}
else {
btnDisplay = '';
btnClass = '';
switch (button) {
case 'ellipsis':
btnDisplay = '…';
btnClass = 'disabled';
break;
case 'first':
btnDisplay = lang.sFirst;
btnClass = button + (page > 0 ? '' : ' disabled');
break;
case 'previous':
btnDisplay = lang.sPrevious;
btnClass = button + (page > 0 ? '' : ' disabled');
break;
case 'next':
btnDisplay = lang.sNext;
btnClass = button + (page < pages - 1 ? '' : ' disabled');
break;
case 'last':
btnDisplay = lang.sLast;
btnClass = button + (page < pages - 1 ? '' : ' disabled');
break;
default:
btnDisplay = button + 1;
btnClass = page === button ?
'active' : '';
break;
}
if (btnDisplay) {
node = jQuery('<li>', {
'class': classes.sPageButton + ' ' + btnClass,
'aria-controls': settings.sTableId,
'tabindex': settings.iTabIndex,
'id': idx === 0 && typeof button === 'string' ?
settings.sTableId + '_' + button :
null
})
.append(jQuery('<a>', {
'href': '#'
})
.html(btnDisplay)
)
.appendTo(container);
settings.oApi._fnBindAction(
node, {action: button}, clickHandler
);
}
}
}
};
attach(
jQuery(host).empty().html('<ul class="pagination"/>').children('ul'),
buttons
);
};
// TableTools Bootstrap compatibility - Required TableTools 2.1+
if (DataTable.TableTools) {
// Set the classes that TableTools uses to something suitable for Bootstrap
jQuery.extend(true, DataTable.TableTools.classes, {
"container": "DTTT btn-group",
"buttons": {
"normal": "btn btn-default",
"disabled": "disabled"
},
"collection": {
"container": "DTTT_dropdown dropdown-menu",
"buttons": {
"normal": "",
"disabled": "disabled"
}
},
"print": {
"info": "DTTT_print_info"
},
"select": {
"row": "active"
}
});
// Have the collection use a bootstrap compatible drop down
jQuery.extend(true, DataTable.TableTools.DEFAULTS.oTags, {
"collection": {
"container": "ul",
"button": "li",
"liner": "a"
}
});
}
};
var table = $('.js-dataTable-full');
$http({
url: 'https://standards-and-partners-api.azurewebsites.net/documents',
method: 'GET',
headers: {
'Accept': 'application/json'
}
}).then(function (response) {
$scope.documents = response.data.data;
$timeout(function () {
// Init Datatables
bsDataTables();
initDataTableFull();
});
});
// Enable pusher logging - don't include this in production
Pusher.logToConsole = true;
var pusher = new Pusher('--------------', {
cluster: 'eu',
encrypted: true
});
var channel = pusher.subscribe('my-channel');
channel.bind('my-event', function(data) {
table.empty();
table.dataTable()._fnInitialise();
$http({
url: 'https://standards-and-partners-api.azurewebsites.net/documents',
method: 'GET',
headers: {
'Accept': 'application/json'
}
}).then(function (response) {
$scope.documents = response.data.data;
$scope.$apply();
});
});
What should I do to reload my datatable with new data ? Thanks guys.
I'm trying to implement inapp purchases with the plugin cordova-plugin-inapppurchase The products load, but after the products are loaded the products doesn't show.
What's my mistake?
This is my code:
<h3 class="inapp_textw" ng-click="loadProducts()" ng-if="!products">Or Inappp purchases</h3>
<h3 class="inapp_textw" ng-repeat="product in products" ng-click="buy(product.productId)">Or Inappp purchases</h3>
JS
var productIds = ["com.domain.example"]; //I have the correct ID
var spinner = '<ion-spinner icon="dots" class="spinner-stable"></ion-spinner><br/>';
$scope.loadProducts = function() {
console.log("loaded inapp products"); // This logs
$ionicLoading.show({
template: spinner + 'Loading...'
});
inAppPurchase
.getProducts(productIds)
.then(function(products) {
$ionicLoading.hide();
$scope.products = products;
})
.catch(function(err) {
$ionicLoading.hide();
console.log(err);
});
};
$scope.buy = function(productId) {
console.log("buy clicked");
$ionicLoading.show({
template: spinner + 'Acquisto in corso...'
});
inAppPurchase
.buy(productId)
.then(function(data) {
console.log(JSON.stringify(data));
console.log('consuming transactionId: ' + data.transactionId);
return inAppPurchase.consume(data.type, data.receipt, data.signature);
})
.then(function() {
localStorage.setItem('sold', 'true');
$ionicLoading.hide();
if (state == "l2") {
$state.go("12")
}
})
.catch(function(err) {
$ionicLoading.hide();
console.log(err);
});
};
$scope.restore = function() {
console.log("IT WORKS");
$ionicLoading.show({
template: spinner + 'Ripristino degli acquisti in corso...'
});
inAppPurchase
.restorePurchases()
.then(function(purchases) {
$ionicLoading.hide();
console.log(JSON.stringify(purchases));
localStorage.setItem('sold', 'true');
$state.go("12")
})
.catch(function(err) {
$ionicLoading.hide();
console.log(err);
$ionicPopup.alert({
title: 'Something went wrong',
template: 'Check your console log for the error details'
});
});
};
You are just loading product that's why its not appearing.
you have to print it to show as below.
<h3 class="inapp_textw" ng-repeat="product in products" ng-click="buy(product.productId)">{{product}}</h3>
Hii i am new to angular js ,right now i am working on the crud operation in angular js , i dont know how to do update the data in angularjs which is consuming rest api calls. could you pls help me out ?
my view :
<div ng-repeat="phone in phones">
<p>{{ phone.sequenceNumber}}. {{ phone.phoneNumber }} ({{ phone.phoneType }}<span ng-if="phone.isPrimary"> primary</span>)</p>
<button ng-click="updatePhone()" ng-model="phone.phoneNumber" class="btn btn-small btn-primary">update</button>
</div>
</div>
</form>
my controller :
"use strict"
ContactApp.controller("StudentController", [
'$scope',
'$http',
'$state',
'$sce',
'UiString',
'Settings',
'EmergencyContact',
'MissingPersonContact',
'Address',
'Phone',
function($scope, $http,$state, $sce, UiString, Settings, EmergencyContact, MissingPersonContact, Address, Phone
) {
EmergencyContact.getContacts($scope.uid).then(function(contacts) {
$scope.emergencyContacts = contacts;
});
MissingPersonContact.getContacts($scope.uid).then(function(contacts) {
$scope.missingPersonContacts = contacts;
});
Address.getLocalAddress($scope.uid).then(function(address) {
$scope.localAddress = address;
});
Phone.getPhones($scope.uid).then(function(phone1) {
$scope.phones = phone1;
});
$scope.newPhoneNumber = '';
$scope.AddPhone = function() {
console.log("scope.newPhoneNumber",$scope.newPhoneNumber);
var newPhone = Phone.addPhone($scope.newPhoneNumber);
Phone.savePhone($scope.uid, newPhone).then(
function(response) {
$scope.phones.push(newPhone);
return console.log("question", response);
},
function(err) {
return console.log("There was an error "
+ err);
});
};
$scope.updatePhone = function() {
Phone.savePhone1($scope.uid, newPhone).then(
function(response) {
$scope.phones.push(newPhone);
return console.log("question", response);
},
function(err) {
return console.log("There was an error "
+ err);
});
};
}]);
my service :
'use strict';
angular.module('ContactApp')
.service('Phone', ['$q', '$http', 'Settings', function($q, $http, Settings) {
this.getPhones = function(id) {
var deferred = $q.defer();
if (id) {
$http.get(Settings.getSetting('wsRootUrl') +
'/person/phone/v1/' + id + '?token=' + Settings.getToken()).
success(function(response) {
deferred.resolve(response.data);
}).error(function(data, status) {
deferred.reject(status);
});
} else {
deferred.resolve({});
}
return deferred.promise;
};
this.addPhone = function(phoneNumber) {
var model =
{
"pidm": null,
"phoneType": "CELL",
"activityDate": null,
"isPrimary": null,
"phoneNumber": phoneNumber,
"sequenceNumber": null,
"status": null
};
return model;
}
this.savePhone = function(userId, phone) {
var deferred = $q.defer();
console.log(phone);
$http.post( Settings.getSetting('wsRootUrl') +
'/person/phone/v1/' + userId + '?token=' + Settings.getToken()
, [ phone ]).
success(function(response) {
deferred.resolve(response.data);
}).error(function(data, status) {
deferred.reject(status);
});
return deferred.promise;
};
this.updatePhone = function(phoneNumber1) {
var model =
{
"pidm": 123456,
"phoneType": "CELL",
"activityDate": null,
"isPrimary": null,
"phoneNumber": phoneNumber1,
"sequenceNumber": null,
"status": null
};
return model;
}
this.savePhone1 = function(userId, phone1) {
var deferred = $q.defer();
console.log(phone1);
$http.put( Settings.getSetting('wsRootUrl') +
'/person/phone/v1/' + userId + '?token=' + Settings.getToken()
, [ phone1 ]).
success(function(response) {
deferred.resolve(response.data);
}).error(function(data, status) {
deferred.reject(status);
});
return deferred.promise;
};
}]);
~~~EDIT~~~~
Okay from what I gather this is what you want:
In HTML inside of ng-repeat:
<input type="text" ng-model="phone.phoneNumber" />
// at this point when the user types their new phone number in the "phone" object has already been updated (via two-way data binding).
Then if you want to save to database you can send to your service via the controller method $scope.updatePhone with the button.
<button ng-click="updatePhone(phone)">Update</button>
Then in the controller:
$scope.updatePhone = function (phone) {
console.log("this is the updated phone: ",phone);
console.log("this is the updated phones array: ",$scope.phones);
// you should see that the phone number has been updated in scope.
Phone.updatePhone(phone);
// this service call should be a post to the server, not a return object as the object has already been updated.
}
Hope this helps
You can find example here of CRUD operation in AngularJS with Web API to perform Create, Read, Update and Delete functionality. I hope it will be help to you.
CRUD Operation in AngularJS with Web API
It must be the heat...
I have a json object that I want to run through a ng-repeat, should be simple, but alas! it doesn't work.
HTML
<a data-ng-repeat="x in template.menuObj" href="{{ x.link }}">{{ x.name }}</a>
JSON
[
{
"ACL":{
"*":{
"read":true
}
},
"link":"home",
"menu":"main",
"name":"Home",
"order":1,
"objectId":"aDcb0HUXwB",
"createdAt":"2015-08-05T15:29:05.948Z",
"updatedAt":"2015-08-05T15:29:11.915Z"
},
{
"ACL":{
"*":{
"read":true
}
},
"link":"category/the-interesting-stuff",
"menu":"main",
"name":"The Interesting Stuff",
"order":2,
"objectId":"znXfUF0kdJ",
"createdAt":"2015-08-05T15:33:11.332Z",
"updatedAt":"2015-08-05T15:33:39.738Z"
},
{
"ACL":{
"*":{
"read":true
}
},
"link":"category/the-fun-stuff",
"menu":"main",
"name":"The Fun Stuff",
"order":3,
"objectId":"WiPmXdhaOu",
"createdAt":"2015-08-05T15:33:44.667Z",
"updatedAt":"2015-08-05T15:34:06.058Z"
},
{
"ACL":{
"*":{
"read":true
}
},
"link":"category/the-nerdy-stuff",
"menu":"main",
"name":"The Nerdy Stuff",
"order":4,
"objectId":"Z0aSsnpV0B",
"createdAt":"2015-08-05T15:34:09.859Z",
"updatedAt":"2015-08-05T15:34:33.564Z"
},
{
"ACL":{
"*":{
"read":true
}
},
"link":"page/about-me",
"menu":"main",
"name":"About Me",
"order":5,
"objectId":"Gm35DOju7t",
"createdAt":"2015-08-05T15:34:37.759Z",
"updatedAt":"2015-08-05T15:34:55.387Z"
}
]
When I run this, I get 5 empty <a>'s, something like:
<a data-ng-repeat="x in template.menuObj" href="" class="ng-binding ng-scope"></a>
So I guess angular sees the 5 arrays, but somehow the keys are not caught?
EDIT: This is how the json object is created (via parse.com):
var Menu = Parse.Object.extend('Menu');
var query = new Parse.Query(Menu);
query.ascending('order');
query.equalTo('menu', 'main');
query.find().then(function(results){
console.log(JSON.stringify(results));
$scope.template.menuObj = results;
}, function(error){
// error-handling
console.log("Error: " + error.code + " " + error.message);
});
EDIT EDIT: Controller etc.
blogApp.controller('templateCtrl', function($scope, templateService) {
$scope.template = templateService;
var Menu = Parse.Object.extend('Menu');
var query = new Parse.Query(Menu);
query.ascending('order');
query.equalTo('menu', 'main');
query.find().then(function(results){
console.log(JSON.stringify(results));
$scope.template.menuObj = results;
}, function(error){
// error-handling
console.log("Error: " + error.code + " " + error.message);
});
});
templateService is a factory that binds a parent controller. It's important to note that before I started messing with parse.com for this project, the ng-repeat worked just fine when I retrieved ($http) a json object via PHP/MySQL.
EDIT EDIT EDIT: uploaded a screendump of console.log(results);
What's happening is that results is the array object, and you are assigning it to $scope.template.menuObj but the json array doesn't have a name. You could either give it a name:
"menuObj": [
{
"ACL":{
"*":{
"read":true
}
},
"link":"home",
"menu":"main",
"name":"Home",
"order":1,
"objectId":"aDcb0HUXwB",
"createdAt":"2015-08-05T15:29:05.948Z",
"updatedAt":"2015-08-05T15:29:11.915Z"
},
{
"ACL":{
"*":{
"read":true
}
},
"link":"category/the-interesting-stuff",
"menu":"main",
"name":"The Interesting Stuff",
"order":2,
"objectId":"znXfUF0kdJ",
"createdAt":"2015-08-05T15:33:11.332Z",
"updatedAt":"2015-08-05T15:33:39.738Z"
},
{
"ACL":{
"*":{
"read":true
}
},
"link":"category/the-fun-stuff",
"menu":"main",
"name":"The Fun Stuff",
"order":3,
"objectId":"WiPmXdhaOu",
"createdAt":"2015-08-05T15:33:44.667Z",
"updatedAt":"2015-08-05T15:34:06.058Z"
},
{
"ACL":{
"*":{
"read":true
}
},
"link":"category/the-nerdy-stuff",
"menu":"main",
"name":"The Nerdy Stuff",
"order":4,
"objectId":"Z0aSsnpV0B",
"createdAt":"2015-08-05T15:34:09.859Z",
"updatedAt":"2015-08-05T15:34:33.564Z"
},
{
"ACL":{
"*":{
"read":true
}
},
"link":"page/about-me",
"menu":"main",
"name":"About Me",
"order":5,
"objectId":"Gm35DOju7t",
"createdAt":"2015-08-05T15:34:37.759Z",
"updatedAt":"2015-08-05T15:34:55.387Z"
}
];
Or leave it like you have it, but the controller must be like this:
blogApp.controller('templateCtrl', function($scope, templateService) {
$scope.template = templateService;
var Menu = Parse.Object.extend('Menu');
var query = new Parse.Query(Menu);
query.ascending('order');
query.equalTo('menu', 'main');
query.find().then(function(results){
$scope.template = JSON.stringify(results);
}, function(error){
// error-handling
console.log("Error: " + error.code + " " + error.message);
});
});
And the view like this:
<body ng-app="blogApp"><!-- angular.module('blogApp', []); -->
<div ng-controller="templateCtrl" >
<nav ng-repeat="a in template">
{{ a.name }}
</nav>
</div>
</body>
But in the case you want to work with it as you have it you should do it this way:
<body ng-app="blogApp"><!-- angular.module('blogApp', []); -->
<div ng-controller="templateCtrl" >
<nav ng-repeat="a in template.menuObj">
{{ a.get('name') }}
</nav>
</div>
</body>