ngdialog not update table after create new item - angularjs

I'm using AngularJS and have the following problem with ngdialog.
I have a function that opens a dialog and then saving dialog form elements which are then displayed in a table.
The table is updated without reloading the page, but to reopen the dialog goes with previous data.
I want to add a new item without reloading the page. Now I do, but I have to reload the page because when recreating another I get with the new data from the previous dialog
var app = angular.module('AlarmsAddOn', ['ngTable', 'ngDialog'])
app.controller('AlarmsAddOnCtrl', function($scope, $http, $filter, ngTableParams, datas, ngDialog, tags, tagIndex, $timeout){
var self=this;
//initializing $scope
$scope.data=datas;
$scope.tagss=tags;
$scope.tagIndex=tagIndex;
$scope.tableParams = new ngTableParams({
page: 1,
count: 10,
filter: {
message: ''
},
sorting: {
tag_id: 'asc'
}
},
{
total: $scope.data.length,
counts:[],
getData: function($defer, params) {
var orderedData = params.sorting() ?
$filter('orderBy')($scope.data, params.orderBy()) :
$scope.data;
params.total(orderedData.length);
$defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
}
});
//edit tag settings
self.edit_addon = function(key){
$http.post('/', key).then(function(results){
if (results.status==201)
{
$scope.typemsg="alert alert-success";
$scope.msgmsg = "The tag settings has been updated. The new Trigger Value is: "+key.value;
$scope.alertmsg = false;
$timeout(function () { $scope.alertmsg = true; }, 2000);
}
else
{
$scope.typemsg="alert alert-danger";
$scope.msgmsg = "Server Error";
$scope.alertmsg = false;
$timeout(function () { $scope.alertmsg = true; }, 2000);
}
});
};
//delete tag settings
self.delete_addon = function(key){
if(confirm("Are you sure to remove the tag settings")){
var url='/'+key.tag_id+'/'+key.trigger;
$http.delete(url).then(function (results) {
console.log(results);
if (results.status==200)
{
for(var i=0; i<$scope.data.length; i++)
{
if($scope.data[i].tag_id == key.tag_id && $scope.data[i].trigger == key.trigger)
{
var p=i;
}
}
$scope.data.splice(p,1);
$scope.tableParams.reload();
$scope.typemsg="alert alert-success";
$scope.msgmsg = "The tag settings of "+key.tag_name+" has been deleted";
$scope.alertmsg = false;
$timeout(function () { $scope.alertmsg = true; }, 2000)
}
else
{
$scope.typemsg="alert alert-danger";
$scope.msgmsg = "Server Error";
$scope.alertmsg = false;
$timeout(function () { $scope.alertmsg = true; }, 2000);
}
});
}
};
//create new tag settings
self.savetag = function () {
$scope.tag=self.tag;
$http.post('/', $scope.tag).then(function (results) {
if (results.status==201)
{
$scope.data.unshift(self.tag);
$scope.tableParams.reload();
// window.location.reload();
}
else
{
}
});
ngDialog.close();
};
//show form to add new tag settings
self.insert_modal_windows_addon = function()
{
ngDialog.open({ template: '/assets/insert.html', controller: 'AlarmsAddOnCtrl', scope: $scope, cache: false});
};
});
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h3>Add New Tag</h3>
<form name="tag_form" ng-submit="AOC.savetag()" >
<select class="form-control" name="tagid" placeholder="Tag Id" ng-model="AOC.tag.tag_id">
<option value="" disabled selected>Tag Name</option>
<option ng-repeat="k in tagss" value="{{k}}">{{tagIndex[k]}}</option>
</select>
<select class="form-control" name="tagtriggertype" placeholder="Trigger Type" ng-model="AOC.tag.trigger" style="margin:20px auto;">
<option value="" disabled selected style="color:#333;">Trigger Type</option>
<option value="hight">hight</option>
<option value="low">low</option>
</select>
<input type="number" class="form-control" name="tagtriggervalue" placeholder="Trigger Value" ng-model="AOC.tag.value", style="margin:20px auto;"/>
<button class="btn btn-sm btn-primary" type="submit">
<span class="glyphicon glyphicon-floppy-save"></span>
Submit
</button>
</form>
</div>
</body>
</html>

Related

Clearing emails after sending in angular

I'm trying to figure out how I can clear the emails in the list. I've managed to create a function where I can remove emails one by one. But I can't seem to find a way on how to clear them all after sending clicking the send invite button.
I'm working on project using angular.js and below is a sample of the code that is a work in progress
<div class="content referral-sender-page">
<div class="wrapper">
<div class="main" ng-controller="ReferralDispatchController">
<h1 class="h large">Send Invites</h1>
<!-- TODO: Explanatory text -->
<div>
<section class="grid__item bp-md-one-third">
<h5 class="h medium gray">To</h5>
<span ng-repeat="e in emails" class="h small email-list">
<span remove-on-click ng-click="removeEmail(e)" class="email-item">{{ e }} <small class="close">X</small></span>
</span>
<div class="col-2">
<input class="input" type="email"
ng-model="email"
placeholder="Email">
<a ng-click="addEmail()" class="button pads primary" >+</a>
</div>
</section>
<section class="grid__item bp-md-two-thirds">
<h5 class="h medium gray">Message</h5>
<p>Write a message to send to your homies with your invite</p>
<textarea class="text-input" ng-model="message" rows="5">
This is awesome and you should try it!
</textarea>
</section>
</div>
<div class="space--bottom one-whole">
<a ng-click="sendReferral()" class="button pads primary">Send Email Invite</a>
</div>
</div>
</div>
</div>
var ctrls = angular.module('elstudio.controllers.site');
//Removes Element only
// ctrls.directive('removeOnClick', function() {
// return {
// link: function(scope, elt, attrs) {
// scope.removeEmail = function() {
// elt.remove();
// };
// }
// }
// });
ctrls.controller('ReferralDispatchController', function ($scope, UserService,
ReferralService) {
$scope.emails = [];
$scope.message = '';
$scope.removeEmail = function(e) {
var index = $scope.emails.indexOf(e);
$scope.emails.splice(index, 1);
};
$scope.addEmail = function() {
if (!$scope.email) {
$scope.$emit('notify', { message: 'Please provide a valid email address' });
return;
}
// If email already in list, ignore
// FIXME: Provide feedback
if ($scope.emails.indexOf($scope.email) != -1) {
$scope.email = '';
return;
}
$scope.emails.push($scope.email);
$scope.email = '';
};
$scope.sendReferral = function() {
if (!$scope.loginUser) {
$scope.$emit('notify', { message: 'Please sign up or log in to your Electric account.',
duration: 3000 });
angular.element('html, body').animate({ scrollTop: 0 }, 'slow');
angular.element('.login-toggle').click();
return;
}
if ($scope.email != '') {
$scope.emails.push($scope.email);
}
if (!$scope.emails) {
$scope.$emit('notify', { message: 'Please provide at least one email address' });
return;
}
var refer = {
emails: $scope.emails,
message: $scope.message
};
var sendSuccess = function() {
$scope.$emit('notify', { message: 'An invitation has been sent!',
duration: 4000 });
};
var sendFailed = function(error) {
// Retry?
$scope.$emit('notify', { message: "Couldn't send invitation",
duration: 4000 });
};
ReferralService.email(refer).$promise.then(sendSuccess, sendFailed);
};
});
$scope.email = []; used to clear the array.
var sendSuccess = function() {
$scope.$emit('notify', { message: 'An invitation has been sent!',
duration: 4000 });
$scope.email = [];
};
Please Use
var refer = {
emails: angular.copy($scope.emails),
message: angular.copy($scope.message)
};
Please view the detail
It will do deep copy. So when we change the value in $scope.emails and $scope.message copied value will not change
also clear the $Scope.email value in the sendSuccess function

How To Update Page After Calling $http.put service in Directive Using AngularJS/Web API/Angular-ui-router

We are new to AngularJS but are working on an AngularJS/Web API application that updates a data model from an AngularJS Bootstrap popover/directive.
We've successfully updated the database from the directive/popover, however are having trouble figuring out how to refresh the data on the page with the updated data without reloading the page.
Main Page CSHTML:
<div ng-app="FFPA" ng-controller="myCtrl">
<div svg-floorplan="dataset"></div>
</div>
Popover HTML:
<div>
<div>
ID: {{ person.Id }}<br />
Name: {{ person.fullName }}<br />
Current Cube/Office: {{ person.seatId }}
<br />
Dept: {{ person.deptId }}
<br />
Job Desc: {{ person.jobDesc}}
<br />
Phone:{{ person.phone}}
<br />
<!--<input type="button" value="Click Me" ng-click="changeName()">-->
</div>
<div class="hiddenDiv" ng-hide="toggle">
<div class="form-group">
<label for="floor">Floor</label>
<input id="floor" ng-model="person.floor" type="text" ng-trim="true" class="form-control" />
</div>
<div class="form-group">
<label for="section">Section</label>
<input id="section" ng-model="person.section" ng-trim="true" type="text" class="form-control" />
</div>
<div class="form-group">
<label for="offCubeNum">offCubeNum</label>
<input id="offCubeNum" ng-model="person.offCubeNum" ng-trim="true" type="text" class="form-control" />
</div>
<div class="form-group">
<label for="cbCube">Cubicle?</label>
<input id="cbCube" ng-model="person.cbCube" type="checkbox" size="1" class="checkbox" />
</div>
</div>
<div ng-hide="buttonToggle">
<input type="button" value="Move" class="btn btn-success" ng-click="moveEmp()">
<input type="button" value="Term" class="btn btn-danger" ng-click="changeName()">
</div>
<div ng-hide="submitToggle">
<input type="button" value="Submit" class="btn btn-success" ng-click="submitMove()">
<input type="button" value="Cancel" class="btn btn-warning" ng-click="cancel()">
</div>
</div>
The main page initially gets data from a service in the angular controller:
var app = angular.module('FFPA', ['ngAnimate', 'ngSanitize', 'ui.bootstrap', 'ui.router']);
app.controller('myCtrl', function ($scope, dataService) {
$scope.test = 'test';
dataService.getData().then(function (data) {
//The reduce() method reduces the array to a single value.
$scope.dataset = data.reduce(function (obj, item) {
obj[item.seatId.trim()] = item;
item.fullName = item.fName + ' ' + item.lName;
item.deptId = item.deptId;
item.jobDesc = item.jobDesc;
item.phone = item.phone;
return obj;
}, {});
});
});
Get Data Service:
angular.module('FFPA').service('dataService', function ($http) {
this.getData = function () {
//web api call
return $http.get("api/Controller/GetData).then(
function (response) {
return response.data;
}, function () {
return { err: "could not get data" };
}
);
}
});
The Update Service is called from the Popover Directive.
Update Service:
angular.module('FFPA').service('updateService', function ($http) {
this.putData = function (oc) {
//web api call
return $http.put("api/Controller/PutUpdateData", oc).then(
function (response) {
return response.data;
}, function () {
return { err: "could not update data" };
}
);
}
});
Here is a snippet from our Popover directive where the update occurs and where we thought we could refresh the scope, and the data for the page:
updateService.putData(data).then(function (response) {
if (response == false)
alert("Move Failed!");
else {
alert("Move Succeeded.");
//$window.location.reload() causes a page reload..not desirable
//$window.location.reload();
$state.reload();
}
});
We tried a $state.reload(); in the popover directive just after updateService.putData(data), however this caused -> Error: Cannot transition to abstract state '[object Object]' error.
Here is the full Popover Directive:
angular.module('FFPA').directive('svgFloorplanPopover', ['$compile', 'updateService', 'vacancyService', 'addService', 'terminateService', '$window', '$state', function ($compile, updateService, vacancyService, addService, terminateService, $window, $state) {
return {
restrict: 'A',
scope: {
'person': '=svgFloorplanPopover',
//UPDATE 8-MAY-2017
onDataUpdate: '&'
},
link: function (scope, element, attrs) {
scope.moveToggle = true; //hide move toggle
scope.addToggle = true; //hide add toggle
scope.submitToggle = true; //hide submit toggle
scope.$watch("person", function () {
if (scope.person) {
if (scope.person.vacant == true) {
scope.addToggle = false; //show add button
scope.empInfoToggle = true; //hide emp info
}
else
scope.moveToggle = false; //show move
}
});
//add employee---------------------------------------------------------
scope.addEmp = function () {
scope.addToggle = scope.addToggle === false ? true : false;
scope.buttonToggle = true;
scope.submitToggle = false;
var data = {
deptId: scope.person.deptId,
divisionId: scope.person.divisionId,
empId: scope.person.empId,
floor: scope.person.floor,
fName: scope.person.fName,
lName: scope.person.lName,
jobDesc: scope.person.jobDesc,
officeCode: scope.person.officeCode,
phone: scope.person.phone,
section: scope.person.section,
seat: scope.person.seat,
seatId: scope.person.seatId,
seatTypeId: scope.person.seatTypeId,
vacant: scope.person.vacant
};
//call to update/move the employee
//updateService.putData(scope.person).then(function () {
addService.putData(data).then(function (response) {
if (response == false)
alert("Create Failed!");
else {
alert("Create Succeeded.");
//UPDATE 8-MAY-2017
$scope.onDataUpdate({ person: $scope.person, moreData: $scope.moreData });
//$window.location.reload();
//$route.reload();
//scope.toggle = false;
}
});
}
//cancel function---------------------------------------------------------
scope.cancel = function () {}
//Term emp---------------------------------------------------------
scope.termEmp = function () {
var data = {
seatId: scope.person.seatId,
floor: scope.person.floor
};
terminateService.putData(data).then(function (response) {
if (response == false)
alert("Term Failed!");
else {
alert("Term Succeeded.");
$window.location.reload();
//$route.reload();
//scope.toggle = false;
}
});
}
//move employee---------------------------------------------------------
scope.moveEmp = function () {
scope.toggle = scope.toggle === false ? true : false;
scope.buttonToggle = true;
scope.submitToggle = false;
if (scope.person && scope.person.fullName.indexOf('changed') === -1) {
//scope.person.fullName += ' move?';
}
//Json object to send to controller to check for vacancy
var data = {
floor: scope.person.floor,
section: scope.person.section,
seat: scope.person.offCubeNum
};
//can't send object via $http.get (?) stringigy json and cast to Office object in controller.
var json = JSON.stringify(data);
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//CHECK VACANCY service call
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
vacancyService.getData(json)
.then(function (response) {
if (response == false)
alert("cube/office occupied");
else{
//+++++++++++++++++++++++++++++++++++++++++++
//UPDATE service call
//+++++++++++++++++++++++++++++++++++++++++++
//CONSTS
var CONSTFLOORPREFIX = "f";
var CONSTSEAT = "s";
var CONSTC = "c"
var floor = scope.person.floor;
var section = scope.person.section;
var offCube = scope.person.offCubeNum;
scope.person.oldSeatId = scope.person.seatId;
var newOfficeId = CONSTFLOORPREFIX + floor + CONSTSEAT; //f3s
//IF CUBE
if (scope.person.cbCube) {
var trimSection = section.trim();
newOfficeId += trimSection + CONSTC; //f3s313c
var trimOffCube = offCube.trim();
newOfficeId += trimOffCube;
}
else {
newOfficeId += 0 + CONSTC + section; //f3s0c
}
scope.person.seatId = newOfficeId;
//Json object to send to controller to check for vacancy
var data = {
Id: scope.person.Id,
seatId: scope.person.seatId,
oldSeatId: scope.person.oldSeatId,
empId: scope.person.empId,
lName: scope.person.lName,
fName: scope.person.fName,
refacName: scope.person.refacName,
deptId: scope.person.deptId,
divisionId: scope.person.divisionId,
jobDesc: scope.person.jobDesc,
seatTypeId: scope.person.seatTypeId,
officeCode: scope.person.officeCode,
phone: scope.person.phone,
floor: scope.person.floor,
section: scope.person.section,
seat: scope.person.seat,
vacant: scope.person.vacant
};
//call to update/move the employee
//updateService.putData(scope.person).then(function () {
updateService.putData(data).then(function (response) {
if (response == false)
alert("Move Failed!");
else {
alert("Move Succeeded.");
//$window.location.reload();
$state.reload();
//$route.reload();
//scope.toggle = false;
}
});
}//end else
});
}
if (element[0].querySelector('text') != null){
scope.htmlPopover = './HTML/popoverTemplate.html';
element[0].setAttribute('uib-popover-template', "htmlPopover");
element[0].setAttribute('popover-append-to-body', 'true');
element[0].setAttribute('popover-trigger', "'click'");
//element[0].setAttribute('popover-trigger', "'mouseenter'");
element[0].setAttribute('popover-placement', 'right');
element[0].removeAttribute('svg-floorplan-popover');
$compile(element)(scope);
}
}
}
}]);
UPDATED: 8-MAY-2017
Originally there is one additional data service and a directive that we left out of this post since it may be considered not essential information, however recently added since it may be needed.
SVG Load Directive:
angular.module('FFPA').directive('svgFloorplan', ['$compile', function ($compile) {
return {
restrict: 'A', //restrict attributes
templateUrl: './SVG/HQ3RD-FLOOR3v10.svg',
scope: {
'dataset': '=svgFloorplan'
},
link: {
pre: function (scope, element, attrs) {
//filter groups based on a cube/office id
var groups = element[0].querySelectorAll("g[id^='f3']");
//groups.style("pointer-events", "all");
scope.changeName = function (groupId) {
if (scope.dataset[groupId] && scope.dataset[groupId].lastName.indexOf('changed') === -1) {
scope.dataset[groupId].lastName += ' changed';
}
}
groups.forEach(function (group) {
var groupId = group.getAttribute('id');
if (groupId) {
//set vacancy colors on vacant cubes
scope.$watch("dataset", function () {
if (scope.dataset) {
if (typeof scope.dataset[groupId] !== "undefined") {
//vacant cubes and offices hover
if (scope.dataset[groupId].vacant == true) {
//seat type id 1 = cube
if (scope.dataset[groupId].seatTypeId == 1){
d3.select(group).select("rect").style("fill", "#99ff33").style("opacity", 0.4)
.style("pointer-events", "all")
.on('mouseover', function () {
d3.select(this).style('opacity', 0.9);
})
.on('mouseout', function () {
d3.select(this).style('opacity', 0.4);
})
}
//vacant office
else {
d3.select(group).select("path").style("stroke", "#ffffff").style("opacity", 1.0);
d3.select(group).select("path").style("fill", "#99ff33").style("opacity", 0.4)
.style("pointer-events", "all")
.on('mouseover', function () {
d3.select(this).style('opacity', 0.9);
})
.on('mouseout', function () {
d3.select(this).style('opacity', 0.4);
})
}
}
else { //Occupied
//seat type id 1 = cube
if (scope.dataset[groupId].seatTypeId == 1) {
d3.select(group).select("rect").style("fill", "#30445d").style("opacity", 0.0)
.style("pointer-events", "all")
.on('mouseover', function () {
d3.select(this).style('opacity', 1.0);
d3.select(group).select('text').style("fill", "#FFFFFF");
})
.on('mouseout', function () {
d3.select(this).style('opacity', 0.0);
d3.select(group).select('text').style("fill", "#000000");
})
//TODO: cubes have rects and on the north side of the building wall, paths.
d3.select(group).select("path").style("fill", "#30445d").style("opacity", 0.0)
.style("pointer-events", "all")
.on('mouseover', function () {
d3.select(this).style('opacity', 1.0);
d3.select(group).select('text').style("fill", "#FFFFFF");
})
.on('mouseout', function () {
d3.select(this).style('opacity', 0.0);
d3.select(group).select('text').style("fill", "#000000");
})
}
//occupied office
else {
//d3.select(group).select("path").style("stroke", "#ffffff").style("opacity", 0.8);
d3.select(group).select("path").style("fill", "#5A8CC9").style("opacity", 1.0)
.style("pointer-events", "all")
.on('mouseover', function () {
//alert("office");
d3.select(this).style("fill", "#2d4768").style('opacity', 1.0);
d3.select(group).selectAll('text').style("fill", "#FFFFFF");
})
.on('mouseout', function () {
d3.select(this).style("fill", "#5A8CC9").style('opacity', 1.0);
d3.select(group).selectAll('text').style("fill", "#000000");
})
}
}//end occupied else
}
}
});
//UPDATE 8-MAY-2017->Implementation Question
scope.onDataUpdateInController = function (person, moreData) { };
var datasetBinding = "dataset['" + groupId + "']";
group.setAttribute('svg-floorplan-popover', datasetBinding);
//UPDATE 8-MAY-2017
//on-data-update corresponds to onDataUpdate item on svgFloorplanPopover's scope.
group.setAttribute('on-data-update', onDataUpdateInController);
$compile(group)(scope);
}
});
}
}
}
}]);
Vacancy Service (check before update):
angular.module('FFPA').service('vacancyService', function ($http) {
...
}
The main question is:
How can we have our application refresh our page with the updated data without reloading the page?
We used to be able to do this in UpdatePanels in ASP.Net webforms back in the day. I think they were partial postbacks/AJAX calls..
EDITED 2-AUG-2017
+++++++++++++++++++++++++++++++++++
Even though the bounty was automatically awarded, we still don't have an answer to this question. Without any implementation context the answers given are not useful.
Can anyone expand on the answers given to give us an idea on how this problem can be solved?
Thanks
Just add your data on $scope object and use it in your view, whenever you update or modify the data just
eg: consider you have a function to get the data where you are making rest call to your db
$scope.getdata=function(){
$http.get(url).success(function(data)
{ $scope.data=data;
});
Whenever you modify your data just call this function in your case on click of close of directive/popup
To refresh your view (not bind the received data) use the answers for the following questions:
Using ngRoute Module
How to reload or re-render the entire page using AngularJS
Using ui-router Module
Reloading current state - refresh data
With that I would recommend you to assign the received data to your bounded $scope property.
I'll add a full example after you'll provide an updated plnkr :)
Please try the following steps:
1. Create a method in svgFloorplanPopover directive and call it by passing in the data
In your svgFloorplanPopover directive, add onDataUpdate item in the scope
declaration:
...
scope: {
'person': '=svgFloorplanPopover',
onDataUpdate: '&'
}
...
and where you are trying to reload state, instead of reloading the state or page, call the below code. This is to create an event system which is fired from within the directive to let the controller or parent directive know that data has changed and view can now be updated.
$scope.onDataUpdate({person: $scope.person, moreData: $scope.moreData});
2. Create a method in svgFloorplan to accept the passed data
Since you are using nested directive approach, you'll need to use the below code in svgFloorplan directive.
group.setAttribute('svg-floorplan-popover', datasetBinding);
group.setAttribute('on-data-update', onDataUpdateInController);
on-data-update corresponds to onDataUpdate item on svgFloorplanPopover's scope.
Declare onDataUpdateInController method on the scope of svgFloorplan directive.
scope.onDataUpdateInController = function(person, moreData) {};
The object properties that you pass from within the directive are laid out flat to the number of parameters.
If you need to pass this data further up to your controller where svgFloorplan is declared. Repeat the above two steps for svgFloorplan directive.
I hope this approach is clear. It is no different than what is explained in Angular Directives, section Creating a Directive that Wraps Other Elements and code where a close button is added. Here is the direct link to the code in plunkr.
Just a question: Are you going to use these directives separately from each other? If no, you may try to create one directive instead of making them two. This will reduce complexity.

$http.post() does not work - (AngularJS)

I am trying to create a form with a dropdown input field and a submit button in AngularJS. Everything works fine except the output is empty xD. I am using <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>. And if it's any help on server side I am using PHP Version 5.5.36-1+donate.sury.org~trusty+1.
Here's the Angular code:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $http) {
$scope.myTxt = "You have not clicked submit, yet!";
$scope.show_result = false;
$scope.myFunc = function() {
$scope.myTxt = "You clicked submit!";
$scope.show_result = true;
}
$scope.categories = [
{"value": 0, "categoryname": "standard"},
{"value": 1, "categoryname": "premium"},
{"value": 2, "categoryname": "gold"}
];
$scope.submitData = function() {
$scope.category = {};
console.log($scope.category);
var jsonString = JSON.stringify($scope.category);
$http.post('ServerController.php', jsonString, {'Content-Type': 'application/x-www-form-urlencoded'})
.success(function(data, status) {
$scope.status = status;
$scope.data = data;
});
}
});
Here is the ServerController.php :
$jsonString = file_get_contents('php://input');
$form_data = json_decode($jsonString, true);
if ($form_data != null) {
echo 'Success!!!';
var_dump($form_data);
} else {
echo 'Sorry!!!';
var_dump($form_data);
}
Here is the HTML:
<body ng-app="plunker">
<form ng-submit="myFunc()" ng-controller="MainCtrl">
<label><b>Category:</b></label>
<select ng-model="category" ng-options="x.categoryname for x in categories track by x.value">
<option value="">Choose a Category</option>
</select>
<p><b>Model:</b> {{category}}</p>
<input ng-click="submitData()" type="submit" value="Submit"></input>
<i>{{myTxt}}</i>
<p ng-show="show_result"><b>Submitted result:</b> {{data}}</p>
</form>
</body>
Here is how the form looks on page load:
This is after you select category in the dropdown:
And finally after clicking submit:
Note: The server controller is sending the output in Submitted result ie. Sorry!!!<pre class='xdebug-var-dump' dir='ltr'> <b>array</b> <i>(size=0)</i> <i><font color='#888a85'>empty</font></i> </pre>
Any ideas?

How to disable and showing another button text untill the button is loaded in AngularJS?

How to disable the button untill the button is loaded in AngularJS?
This is my directive for indicate data loading status, and disable button untill $http request is processed.
But the problem is when i reload the page the button will automatically disable and reloaded.How to restrict that?
One more issue.
If I have two more button in the same page when i submit one of that button the entire button will disable and showing loading...
I need two things
When a page is loaded the the other buttons are not disable not showing loading...I want to disable the entire page and currrent submit button should be shown loading...
if one button is submit the other butttons are not showing loading...
This is my code script.js
var myApp = angular.module("myApp", []);
myApp.controller("myCtrl", function($scope, $http, $timeout) {
$scope.save = function() {
$http.pendingRequests.length = 1;
$timeout(function() {
$http.pendingRequests.length = 0;
}, 1000);
};
$scope.submit = function() {
$http.pendingRequests.length = 1;
$timeout(function() {
$http.pendingRequests.length = 0;
}, 1000);
};
});
myApp.directive("disableonrequest", function($http,$timeout)
{
return function(scope, element, attrs)
{
scope.$watch(function()
{
return $http.pendingRequests.length > 0;
}, function(request)
{
if (!request)
{
element.attr('disabled', false);
element.html("<span >" + attrs.notloading + "</span>");
}
else
{
element.attr('disabled', true);
element.html("<span >" + attrs.loading + "</span><i class='fa fa-refresh fa-spin'></i>");
}
});
}
});
view.html
<body ng-app="myApp" ng-controller="myCtrl">
<button ng-click="save()" loading="Loading..." notloading="Save" disableonrequest></button>
<button ng-click="submit()" loading="Loading..." notloading="Submit" disableonrequest></button>
</body>
When i click on each button both button will disable and show loading...
how to restrict that?
I want to disable the entire page when a button is clicked and submitted button should be shown loading...
Please help me. I am new in Angular JS
This happens because your $watch depends on the global variable $http.pendingRequests. And when the value of the variable changes, then angular starts change function for the two directives.
To avoid this, use different variables to store values loading. Example can watch jsfiddle
var myApp = angular.module("myApp", []);
myApp.controller("myCtrl", function($scope, $http, $timeout) {
$scope.saving = false;
$scope.submiting = false;
$scope.save = function() {
$http.pendingRequests.length = 1;
$scope.saving = true;
$timeout(function() {
$scope.saving = false;
$http.pendingRequests.length = 0;
}, 1000);
};
$scope.submit = function() {
$scope.submiting = true;
$http.pendingRequests.length = 1;
$timeout(function() {
$scope.submiting = false;
$http.pendingRequests.length = 0;
}, 1000);
};
});
myApp.directive("disableonrequest", function() {
return {
restrict: 'A',
scope: {
notloading: "#",
loading: "#",
proccess:"=",
},
link: function(scope, element, attrs) {
scope.$watch('proccess', function(request) {
console.log(request,element);
if (!request) {
element.attr('disabled', false);
element.html("<span >" + scope.notloading + "</span>");
} else {
element.attr('disabled', true);
element.html("<span >" + scope.loading + "</span><i class='fa fa-refresh fa-spin'></i>");
}
});
},
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
<button ng-click="save()" loading="Loading..." proccess="saving" notloading="Save" disableonrequest></button>
<button ng-click="submit()" loading="Loading..." proccess="submiting" notloading="Submit" disableonrequest></button>
</body>
UPDATED
Solution with block all page.
Live example on jsfiddle
var myApp = angular.module("myApp", []);
myApp.controller("myCtrl", function($scope, $http, $timeout) {
$scope.pendingRequests = $http.pendingRequests;
$scope.save = function() {
$http.pendingRequests.length++;
$timeout(function() {
$http.pendingRequests.length--;
}, 1000);
};
$scope.submit = function() {
$http.pendingRequests.length++;
$timeout(function() {
$http.pendingRequests.length--;
}, 1000);
};
});
myApp.directive("blockWhileLoad", function() {
return {
restrict: 'EA',
replace:true,
transclude:true,
scope: {
proccess: "=",
},
template:'<div><div ng-transclude></div><div ng-class="{\'blocker\':proccess>0}"></div></div>',
link: function(scope, element, attrs) {
},
}
});
.errors {
color: maroon
}
.blocker
{
position: fixed;
top: 0px;
left: 0px;
bottom: 0px;
right: 0px;
z-index: 1038;
background: rgba(0,0,0,.2);
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
<fieldset ng-disabled="pendingRequests.length>0">
<input />
<button ng-click="save()">Save</button>
<button ng-click="submit()">Submit</button>
</fieldset>
<block-while-load proccess="pendingRequests.length">
<input />
www.google.com
<button ng-click="save()">Save</button>
<button ng-click="submit()">Submit</button>
</block-while-load>
</body>
Remember, angularjs use promises and the $http service extend $q, so you can use promises with that service.
From: https://docs.angularjs.org/api/ng/service/$http
//Before the request, set element as loading
element.attr('disabled', true);
element.html("<span >" + attrs.loading + "</span><i class='fa fa-refresh fa-spin'></i>");
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// when the http is fully loaded, set visible
element.attr('disabled', false);
element.html("<span >" + attrs.notloading + "</span>");
}, function errorCallback(response) {
// show an error message or just put the button available again
element.attr('disabled', false);
element.html("<span >" + attrs.notloading + "</span>");
});

how to set function or get value from parameters on select change in angular.js

I am newer in anguler and want a value on change from select option and want to update status of particular ID. I have setup some code but this is not working. can you help me.
fetch data and get it on data and after that setup a select box
<select ng-model="newStatus" ng-change="changeNewStatus(data.id, data.message_status)">
<option value="1" ng-selected="data.message_status == 1">New</option>
<option value="2" ng-selected="data.message_status == 2">Closed</option>
</select>
now i want to print it here {{selectedResult}}
below is my controller where i want to call this function
app.controller('MessageFetchGrid', function ($scope, $http, $timeout) {
$scope.changeNewStatus = function(msgId, msgStatus){
$scope.selectedResult = "msg-id="+msgId+" status= "+msgStatus;
}
});
here is my full code
app.filter('startFrom', function() {
return function(input, start) {
if(input) {
start = +start; //parse to int
return input.slice(start);
}
return [];
}
});
app.controller('MessageFetchGrid', function ($scope, $http, $timeout) {
$http.get('api/v1/loadMessage.php').success(function(data){
$scope.list = data;
$scope.currentPage = 1; //current page
$scope.entryLimit = 25; //max no of items to display in a page
$scope.filteredItems = $scope.list.length; //Initially for no filter
$scope.totalItems = $scope.list.length;
});
$scope.setPage = function(pageNo) {
$scope.currentPage = pageNo;
};
$scope.filter = function() {
$timeout(function() {
$scope.filteredItems = $scope.filtered.length;
}, 10);
};
$scope.sort_by = function(predicate) {
$scope.predicate = predicate;
$scope.reverse = !$scope.reverse;
};
$scope.changeNewStatus = function(msgId, msgStatus){
$scope.selectedResult = "msg-id="+msgId+" status= "+msgStatus;
}
});
you can use ng-options directive :
partial:
<div ng-app="test">
<div ng-controller="TestController">
<select ng-options="item as item.label for item in items track by item.id" ng-model="selected">
<option value="">Select</optipn>
</select>
<span>{{selected}}</span>
</div>
</div>
js:
var app = angular.module("test", []);
app.controller("TestController", ["$scope", function($scope) {
$scope.items = [{
id: 1,
label: 'aLabel'
}, {
id: 2,
label: 'bLabel'
}];
}]);
example
http://codepen.io/anon/pen/MaRMPz

Resources