I wrote the edit method to run when the edit link is clicked. I want it to load the data into text box, and is passing correct way but data is still not showing up in the text boxes.
Admin.js
var app = angular.module("adminmdl", [])
app.controller("admincontroller", function ($scope, AdminService) {
$scope.Action = 'Add';
GetAllCustomer();
function GetAllCustomer() {
var getcust = AdminService.getCustomer();
getcust.then(function (cust) {
$scope.customers = cust.data;
}, function () {
alert('Error');
});
}
$scope.data = {
cus_code: '',
cus_name: ''
}
$scope.savecu = function () {
if ($scope.Action == 'Add') {
AdminService.saveCustomerDdetails($scope.cusmodel).then(function (d) {
GetAllCustomer();
$scope.msg = "Insert Successfully";
}, function () {
$scope.msg = "Error Insert Customer";
});
}
}
$scope.EditCustomer = function (cust) {
$scope.Action = "Update";
AdminService.EditCustomersDetails(cust.cus_code).then(function (d) {
$scope.cust = d.data;
$scope.cust.cus_code = cust.cus_code;
$scope.cust.cus_name = cust.cus_name;
}, function () {
alert('Error Update Records');
});
//GetAllCustomer();
}
})
.service('AdminService', function ($http) {
this.getCustomer = function () {
return $http.get('GetCustomer');
}
this.saveCustomerDdetails = function (customer) {
var request = $http({
method: 'POST',
url: '/Admin/AddCutomer',
data: customer
});
return request;
}
this.EditCustomersDetails = function (CustomerCode) {
var request = $http({
method: 'POST',
url: '/Admin/EditCustomer',
params:{
id:CustomerCode
}
});
return request;
}
})
ASP MVC Method
[HttpPost]
public JsonResult EditCustomer(string id) {
var customerdetails = te.Customerss.Find(id);
return Json(customerdetails, JsonRequestBehavior.AllowGet);
}
HTML Form
<form class="form-horizontal" method="post" name="basic_validate" id="basic_validate" novalidate="novalidate">
<div class="control-group">
<label class="control-label">Customer Code</label>
<div class="controls">
<input type="text" ng-model="cusmodel.cus_code" name="required" id="required" >
</div>
</div>
<div class="control-group">
<label class="control-label">Customer Name</label>
<div class="controls">
<input type="text" ng-model="cusmodel.cus_name" name="name" id="name" >
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" value="Save" ng-click="savecu()" class="btn btn-success">
<input type="submit" value="Clear" class="btn btn-success" />
</div>
</div>
<div class="control-group">
<div class="controls">
<p style="color:green">{{msg}}</p>
</div>
</div>
#*<div class="form-actions">
</div>*#
</form>
Table
<div class="widget-content nopadding">
<table class="table table-bordered data-table">
<thead>
<tr>
<th>Customer Code</th>
<th>Customer Name</th>
</tr>
</thead>
<tbody>
<tr class="gradeX" ng-repeat="cust in customers">
<td>{{cust.cus_code}}</td>
<td>{{cust.cus_name}}</td>
<td>Edit</td>
<td> </td>
</tr>
</tbody>
</table>
</div>
its not working because you are trying to access data object which is not passed in json so either pass data object like
return Json(new {data = customerdetails}, JsonRequestBehavior.AllowGet);
or change
$scope.cust = d.data; To $scope.cust = d;
Related
in this code of HTML, we get input text value and send to the Angular controller
so they get to work as defined in code.
<div class="row" ng-controller="RegionController">
<div class="col-lg-12" >
<div class="hpanel">
<div class="panel-heading">
<!-- <div panel-tools></div> -->
<h2>Region Master Entry</h2>
</div>
<div class="panel-body">
<!--change form name,and submit controller name-->
<form role="form">
<div class="form-group">
<label class="col-sm-2 control-label">Region Name</label>
<div class="col-sm-10">
<input type="text" placeholder="please enter Region name" class="form-control m-b" required name="Region Name" ng-model="formRegionData.region_name" >
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Region Code</label>
<div class="col-sm-10">
<input type="text" placeholder="please enter Region code" class="form-control m-b" required name="Region Code" ng-model="formRegionData.region_code">
</div>
</div>
<div class="form-group">
<div class="col-sm-3">
<label>Active</label>
</div>
<div class="checkbox checkbox-success col-sm-9">
<input id="checkbox3" type="checkbox" checked="" ng-model="formRegionData.status">
<label for="checkbox3">
</label>
</div>
</div>
<div class="form-group">
<div class="col-sm-4"></div>
<div class="col-sm-8">
<button class="btn btn-sm btn-primary btn-xl text-right" type="submit" ng-click="createRegion()"><strong> Save Region </strong></button>
</div>
</div>
{{formRegionData | json}}
</form>
</div>
</div>
</div>
</div>
"{{formRegionData | json}}" this will return in HTML input text result of but not send data to the controller
in Controller the code is written as
.controller('RegionController', function( $scope , regionService) {
$scope.createRegion = function() {
debugger;
vm.processing = true;
vm.message = '';
console.log(formRegionData);
regionService.SaveRegion( formRegionData )
.then(function(data) {
debugger;
//console.log(data);
//.success(function(data) {
vm.processing = false;
vm.storyData = {};
vm.message = data.message;
});
}
})
and my service to work according to Controller
.factory('regionService',function($http ){
var regionFactory = {};
regionFactory.SaveRegion = function(formRegionData) {
debugger;
return $http.post('/api/region/', formRegionData);
}
return regionFactory;
});
You have missed $scope
$scope.createRegion = function() {
debugger;
$scope.processing = true;
$scope.message = '';
console.log($scope.formRegionData);
regionService.SaveRegion($scope.formRegionData )
.then(function(data) {
debugger;
//console.log(data);
//.success(function(data) {
$scope.processing = false;
$scope.storyData = {};
$scope.message = data.message;
});
}
})
and remove ng-click="createRegion()" in your button control and add this code in your form tag by ng-submit. like,
<form ng-submit="createRegion()" role="form">
You have missed of $scope in form region data
Here is the link Jsfiddle
JS
angular.module('myApp', ['ngStorage'])
.controller('RegionController', function($scope, regionService) {
var vm = this;
$scope.createRegion = function() {
debugger;
vm.processing = true;
vm.message = '';
regionService.SaveRegion($scope.formRegionData)
.then(function(data) {
debugger;
//console.log(data);
//.success(function(data) {
vm.processing = false;
vm.storyData = {};
vm.message = data.message;
});
}
}).factory('regionService', function($http) {
var regionFactory = {};
regionFactory.SaveRegion = function(formRegionData) {
debugger;
return $http.post('/api/region/', formRegionData);
}
return regionFactory;
});
Am trying to display the time format data from the firebase database, that I have connected to the angular app, the html tag with the input type"text" is displaying fine on the dashboard but there is the problem with the time format and it is not getting displayed.
Here is the below HTML code
<div class = "row" ng-controller = "taskCtrl" >
<div class = "col-md-5">
<h3> Add Task </h3>
<form ng-submit= "addtask()">
<div class="form-group">
<select ng-model="selectedName" ng-options="X as X.Appname for X in appy">
</select>
</div>
<div class="form-group">
<label >Task Name</label>
<input type="text" class="form-control" ng-model = "tname" placeholder="Task Name">
</div>
<div class="form-group">
<label >Task Description</label>
<input type="text" class="form-control" ng-model = "tdes" placeholder="Task Description">
</div>
<div class="form-group">
<label >Task start time </label>
<input type= "text" class="form-control" ng-model = "tstime" placeholder="Task start time" >
</div>
<div class="form-group">
<label >Task Info</label>
<input type="time" class="form-control" ng-model = "tetime" placeholder="Task end time">
</div>
<div class="form-group">
<label >Phone number</label>
<input type="text" class="form-control" ng-model = "phno" placeholder="Phone number">
</div>
<button type = "submit" class = "btn btn-default">Submit</button>
</form>
</div>
<div class = "col-md-7">
<h3> Contacts</h3>
<table class= "table table-striped">
<thead>
<tr>
<th>Task Name </th>
<th>Task Description</th>
<th>Task Start time </th>
<th>Task End Time </th>
<th> Task Status </th>
</tr>
<tbody>
<tr ng-repeat = "tas in task">
<td> {{tas.tname}}</td>
<td> {{tas.tdes}}</td>
<td> {{tas.tstime}}</td>
<td> {{tas.tetime}}</td>
</tr>
</tbody>
</thead>
</table>
</div>
</div>
Here is the below javascript code :
'use strict';
angular.module('myApp.task', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/task', {
templateUrl: 'views/task.html',
controller: 'taskCtrl'
});
}])
.controller('taskCtrl', ['$scope','$firebaseArray',function($scope, $firebaseArray) {
var ref = new Firebase('https://contactlist9934.firebaseio.com/task');
$scope.task = $firebaseArray(ref);
var ref3 = new Firebase('https://contactlist9934.firebaseio.com/application');
$scope.appy = $firebaseArray(ref3);
$scope.addtask = function(){
var r1;
var r2;
var r3;
var r4;
r1 = $scope.tstime.toString();
r2 = r1.substring(16,24);
r3 = $scope.tetime.toString();
r4 = r3.substring(16,24);
$scope.task.$add({
tname: $scope.tname,
tdes: $scope.tdes,
etime: r2,
ttime: r4,
appname: $scope.selectedName.Appname
}).then(function(ref){
var id = ref.key();
console.log('Added Task' +id);
$scope.name = '';
$scope.email = '';
});
}
}])
.controller('myCtrl', function($scope) {
});
The text fields are getting displayed fine but the time format is not getting diaplayed, help me out on this one !!
You could use a filter for this and convert the tstime and tetime in your controller to your desired format like this:
$scope.tstime = $filter('date')($scope.tstime, 'yyyy/MM/dd');
$scope.tetime = $filter('date')($scope.tetime, 'yyyy/MM/dd');
Or if you want to use a directive and use it in multiple inputs you can make a directive something like this:
.directive('formatDate', ['$timeout', '$filter', function ($timeout, $filter) {
return {
require: 'ngModel',
link: function ($scope, $element, $attrs, $ctrl) {
var dateFormat = 'yyyy/MM/dd';
$ctrl.$parsers.push(function (viewValue) {
var pDate = Date.parse(viewValue);
if (isNaN(pDate) === false) {
return new Date(pDate);
}
return undefined;
});
$ctrl.$formatters.push(function (modelValue) {
var pDate = Date.parse(modelValue);
if (isNaN(pDate) === false) {
return $filter('date')(new Date(pDate), dateFormat);
}
return undefined;
});
$element.on('blur', function () {
var pDate = Date.parse($ctrl.$modelValue);
if (isNaN(pDate) === true) {
$ctrl.$setViewValue(null);
$ctrl.$render();
} else {
if ($element.val() !== $filter('date')(new Date(pDate), dateFormat)) {
$ctrl.$setViewValue($filter('date')(new Date(pDate), dateFormat));
$ctrl.$render();
}
}
});
}
};
}]);
And bind it to your input like this:
<input type= "text" class="form-control" format-date ng-model="tstime" placeholder="Task start time">
<input type="time" class="form-control" format-date ng-model="tetime" placeholder="Task end time">
This is fixed now, as I was trying to fetch the data from the firebase, the below variables should match in the below codes :- -
HTML
<tr ng-repeat = "tas in taski">
<td> {{tas.tname}}</td>
<td> {{tas.tdes}} </td>
<td> {{tas.etime}}</td>
<td> {{tas.ttime}}</td>
<td> {{tas.appname}}</td>
</tr>
Script
$scope.task.$add({
tname: $scope.tname,
tdes: $scope.tdes,
etime: $scope.tstime,
ttime: r4,
appname: $scope.selectedName.Appname
}).then(function(ref)
I want to update data from laravel controller to database,
I am able tto update data in model but I am not able to update data into database
here is my View or HTML coding
function editdata(data)
{
//alert(data);
$(function(){
$.ajax({
method : "GET",
url: "welcome",
data: {id: data},
success : function(response)
{
//debugger;
/*if(response==true)
alert("success");
else
alert("Failure");*/
var a=response;
//$('#fname').value(a.fname);
$('#firstName').val(a.fname);
$('#lastName').val(a.lname);
$('#qualification').val(a.qualification);
$('#emailAddress').val(a.email);
$('#contactmessage').val(a.desc);
var elem = document.getElementById("add");
elem.value="Update";
}
});
});
}
function disableData(data)
{
//alert(data);
//if (confirm('Are You Sure You Want To Delete Data ?')) {
$(function(){
$.ajax({
method : "GET",
url: "welcome/disable",
data: {id: data},
success : function(response)
{
//alert(response);
window.location.reload();
//debugger;
/*if(response==true)
alert("success");
else
alert("Failure");*/
//alert('Data is deleted Successfully!!!');
}
});
});
//} else {
//alert('Data is not deleted');
//}
}
function addUpdateData(data)
{
var btnvalue = document.getElementById("add").value;
//alert($('#firstName').val)
//alert(btnvalue);
if(btnvalue=="Add")
{
$(function(){
$.ajax({
method : "GET",
url: "welcome",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: dataToSend,
success : function(response)
{
alert("data sent successfully");
//debugger;
/*if(response==true)
alert("success");
else
alert("Failure");*/
}
});
});
}
else
{
$(function(){
$.ajax({
method : "GET",
url: "welcome",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: dataToSend ,
success : function(response)
{
alert("data sent successfully");
//debugger;
/*if(response==true)
alert("success");
else
alert("Failure");*/
}
});
});
}
}
/*function addData(data)
{
$function(){
$.ajax({
method : "post",
url: "welcome",
data: {id: data,}
})
}
}*/
</script>
</head>
<body>
<div class="container-fluid" style="background-color: #CCCCCC">
<h1>Temp Form</h1>
<form method="post" action="" role="form">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="panel panel-default ">
<div class="container">
<div class="panel-body">
<div class="form-group">
<label for="firstName">First Name *</label>
<input name="fname" type="text" class="form-control" id="firstName" placeholder="Enter First Name" required>
</div>
<div class="form-group">
<label for="lastName">Last Name *</label>
<input name="lname" type="text" class="form-control" id="lastName" placeholder="Enter Last Name" required>
</div>
<div class="form-group">
<label for="qualification">Qualification *</label>
<input name="qualification" type="text" class="form-control" id="qualification" placeholder="BE, MCA, MBA Etc." required>
</div>
<div class="form-group">
<label for="emailAddress">Email address *</label>
<input name="email" type="email" class="form-control" id="emailAddress" placeholder="Enter Email" required>
</div>
<div class="form-group">
<label for="contactmessage">Message</label>
<textarea name="desc" type="text" class="form-control" id="contactmessage" placeholder="Message" rows="2"></textarea>
</div>
<input type="submit" id="add" class="btn btn-primary" onClick="addUpdateData(id)" value="Add"></button>
</div>
</div>
</div></form>
</div>
<div class="container">
<div class="container-fluid">
<h1>All Data</h1>
<div class="row">
<table class="table table-hover">
<thead>
<tr>
<th> First Name </th> <th> Last Name </th>
<th> Qualification </th> <th> E-mail </th> <th> Description </th>
</tr>
</thead>
<tbody>
#foreach ($forms as $form)
<tr>
<td> {{ $form->fname }} </td>
<td> {{ $form->lname }} </td>
<td> {{ $form->qualification }} </td>
<td> {{ $form->email }} </td>
<td> {{ $form->desc }} </td><br>
<td> <a id="{{ $form->id }}" onClick="editdata(id)" class="btn btn-info">
<span class="glyphicon glyphicon-edit"></span></a></td>
<td><a id="{{ $form->id }}" onClick="disableData(id)" class="btn btn-danger">
<span class="glyphicon glyphicon-trash"></span>
</a></td>
</td>
</tr>
#endforeach
</tbody>
</div>
</div>
</table>
</body>
</html>
Here is code for controller
<?php
namespace App\Http\Controllers;
use DB;
use App\Basicusers;
use Request;
use App\Http\Requests;
class FormController extends Controller
{
//$flag = "Add";
public function show()
{
//return 'FormController';
$forms = Basicusers::all()->where('flag',1);
//$name = ['Nix','Shiv'];
//return view('welcome',compact('name'));
return view('welcome',compact('forms'));
}
/*public function addNew(Request $req)
{
$bs = new Basicusers;
$bs->fname = $req->fname;
$bs->lname = $req->lname;
$bs->qualification = $req->qualification;
$bs->email = $req->email;
$bs->desc = $req->desc;
$bs->save();
return back();
//return "Success";
}*/
public function editdata()
{
//return "Editdata called";
//$data = Basicusers::find($id);
//$flag = "Update";
//return view('edit',compact('data')));
$id = $_GET['id'];
//$id = Request::get();
$data = Basicusers::find($id);
//return view('welcome',compact('id'));
return $data;
//return $id;
// $category = Input::get('productCategory');
//$id = Request::get('id');
//$data = Basicusers::find($id);
//return $data;
// 1exit;
//return $data;
/*htmlForm::open();
Form::textarea('fname','Nirav');
Form::close();
return back()*/;
//$form = Basicusers::find($id);
//return view('welcome',compact('form'));
}
public function disableData()
{
$id = $_GET['id'];
//$update = DB::table('basicusers')->where('id',$id)->update('flag','0' );
$alldata = Basicusers::find($id);
//$original = $alldata->flag;
$alldata->flag = 0;
$alldata->save();
//$alldata.update('flag',0);
//$alldata.save();
//$update->save();
return $alldata->flag;
//Basicusers::find($id)->delete();
//Basicusers::where('id',$id)->update('flag',0);
//return "success";
}
/*public function addUpdateData(Request $request)
{
/*$formupdate = Request::all();
$form = Basicusers::find($id);
$form->update($formupdate);
return redirect('/');*/
//if($flag=="Add")
//print_r("Data Will be Added");
// if($flag=="Update")
// print_r("Data Will be Updated");
//else
//print_r("Error");
//print_r($formupdate);
//$input = Input::all();
//return response()->json($input); //- See more at: http://yuluer.com/page/dehbedif-laravel-5-controller-wont-receive-data-from-ajax-form.shtml#sthash.gj2cIar7.dpuf
}*/
}
I am able to get data using following commands
$id = $_GET['id'];//id of data to be disabled
$alldata = Basicusers::find($id);//row for which data will be disabled
$alldata->flag = 0;//setting values
$alldata->save();//saving data
return $alldata->flag;//returning new value
However from the above code Data is not updated in database
How to update data in database please guide
after clicking on delete button, I just want to disable data(don't want to fetch that row)
I have column called flag where binary values 0 or 1 stored.
I am fetching only those records where the value of flag is 1
so on delete I want to make flag value for that record to 0
Perhaps you can try the alternative laravel update method $alldata->update(['flag' => 0]); and see if you have better luck with that...
I am new to angularJS as well as MVC. Just tried a simple CRUD operation .
The GetallEmployee() and the edit operation call are working fine. However the submit is not working. I am sure there is a lot of blunder in the code .Apologies for that .
Here is my Controller and service and view that I added....
app.controller("myController", ['$scope', '$http', 'angularService', function ($scope, $http, angularService) {
$scope.employees = [];
var fetched = angularService.GetAllEmployee();
fetched.then(function (emps) {
$scope.employees = emps.data;
});
$scope.editEmployee = function (data) {
var Emp = $http({
method: "get",
url: "Home/GetEmployeebyId",
params: {
Id: JSON.stringify(data.ID)
}
}).success(function (Emp) {
$scope.employeeName = Emp.Name;
$scope.employeeId = Emp.ID;
$scope.employeeEmail = Emp.Email;
$scope.employeeAge = Emp.Age;
$scope.Action = "Update";
$scope.IsIndian = Boolean(Emp.IsIndian);
$scope.employeeGender = Emp.Gender;
});
};
$scope.AddUpdateEmployee = function () {
var Employee = {
Id: $scope.employeeId,
Name: $scope.employeeName,
Email: $scope.employeeEmail,
Age: $scope.employeeAge,
Gender: $scope.employeeGender,
IsIndian: $scope.IsIndian,
};
var getAction = $scope.Action;
if (getAction == 'Update') {
Employee.Id = $scope.employeeId;
$http({ method: 'post', url: 'Home/UpdateEmployee', data: JSON.stringify(Employee), datatype: 'json' }).success
(function (output) {
var fetched = angularService.GetAllEmployee();
fetched.then(function (emps)
{
$scope.employees = emps.data;
}
)
ClearFields();
});
}
else {
$http({ method: 'post', url: 'Home/AddEmployee', data: JSON.stringify(Employee), datatype: 'json' }).success
(function () {
var fetched = angularService.GetAllEmployee();
fetched.then(function (emps) {
$scope.employees = emps.data;
alert(output);
ClearFields();
});
}
);
}
$scope.Action = "";
}
////$scope.deleteEmployee = function (employee) {
//// angularService.deleteEmployee(employee.ID).then(function (msg) {
//// GetAllEmployee();
//// alert(msg.data);/////earlier it was a string message in place if msg.data
//// }, function () {
//// alert('Error in Deleting Record');
//// });
////}
function ClearFields() {
$scope.employeeId = "";
$scope.employeeName = "";
$scope.employeeEmail = "";
$scope.employeeAge = "";
$scope.IsIndian = false;
$scope.Gender = 'Male';
}
}]);
app.service("angularService", function ($http) {
//get All Eployee
var temp = this;
temp.employee = [];
this.GetAllEmployee = function () {
return $http.get("Home/GetAll").success(function (emps) {
emps.forEach(function (eachemp) {
eachemp.IsIndian = Boolean(eachemp.IsIndian);
temp.employee.push(eachemp);
})
});
}
});
#{
ViewBag.Title = "Home Page";
}
<div ng-controller="myController as myController" ng-app="MyApp">
<br />
<div>
<table class="table ">
<tr>
<td colspan="6" align="center">
<label style="font-family:Arial ;font-weight:bold">Employee Details</label>
</td>
</tr>
<tr>
<td style="font-weight:bold">Name</td>
<td style="font-weight:bold">Id</td>
<td style="font-weight:bold">Email</td>
<td style="font-weight:bold">Age</td>
<td style="font-weight:bold"></td>
</tr>
<tr ng-repeat="emp in employees">
<td>{{emp.Name}}</td>
<td>{{emp.ID}}</td>
<td>{{emp.Email}}</td>
<td>{{emp.Age}}</td>
<td>
<button ng-click="editEmployee(emp)" type="submit" class="btn btn-primary">Edit</button>
<button ng-click="deleteEmployee(emp)" type="submit" class="btn btn-primary">Delete</button>
</td>
<td>
<input type="checkbox" ng-model="emp.IsIndian" disabled="disabled" name="IndianChk" /> Indian
<input type="radio" disabled="disabled" ng-model="emp.Gender" value="Male"> Male
<input type="radio" disabled="disabled" ng-model="emp.Gender" value="Female" />Female
</td>
</tr>
</table>
</div>
<form name="form" ng-submit="myController.addupdateemployee()">
<table class="table table-responsive">
<tr>
<td>
<label>Employee ID </label>
</td>
<td>
<input type="text" disabled="disabled" ng-model="employeeId" class="form-control" />
</td>
</tr>
<tr>
<td>
<label>Employee Name </label>
</td>
<td>
<div class="form-group" ng-class="{'has-error': form.empname.$invalid && form.empname.$dirty }">
<input type="text" ng-model="employeeName" class="form-control" required name="empname" />
</div>
</td>
</tr>
<tr>
<td>
<label>Employee Email </label>
</td>
<td>
<div class="form-group" ng-class="{'has-error': form.mail.$invalid && form.mail.$dirty }">
<input type="text" ng-model="employeeEmail" class="form-control" required name="mail" />
</div>
</td>
</tr>
<tr>
<td>
<label>Gender</label>
</td>
<td>
<div>
<select class="form-control" ng-model="employeeGender" required>
<option>Male</option>
<option>Female</option>
</select>
</div>
</td>
</tr>
<tr>
<td>
<label>Employee Age </label>
</td>
<td>
<div class="form-group">
<input type="number" ng-model="employeeAge" required class="form-control" name="age">
</div>
</td>
</tr>
<tr>
<td>
<label>Is Indian </label> <input type="checkbox" ng-model="IsIndian" ng-required="true" />
</td>
</tr>
<tr>
<td colspan="2">
<button type="submit" class="btn btn-primary" name="submit">submit</button>
</td>
</tr>
</table>
</form>
</div>
Change your form tag from:
<form name="form" ng-submit="myController.addupdateemployee()">
to
<form ng-submit="AddUpdateEmployee()" ng-controller="myController">
I'm new to angular, currently having a problem with updating a table data on form submit. This is my view:
<div class="container-fluid">
<div class="row">
<div class="col-md-12" ng-controller="feeStatement">
<panel panel-class="panel-sky" heading="Add Fee Details">
<panel-controls>
<panel-control-collapse></panel-control-collapse>
</panel-controls>
<div id="alert" class="alert alert-danger hide">
<strong>Error</strong> Unable to save the course data.<br><br>
<ul>
<li id="error"></li>
</ul>
</div>
<form ng-submit="submit(credentials)" ng-controller="feeStatement" class="form-horizontal row-border">
<div class="form-group">
<label for="fieldname" class="col-md-3 control-label">Item Description</label>
<div class="col-md-6">
<textarea name="description" id="fieldabout" class="form-control autosize" rows="2" ng-model="credentials.description"></textarea>
</div>
</div>
<div class="form-group">
<label for="fieldname" class="col-md-3 control-label">Due Date</label>
<div class="col-md-6">
<datepicker ng-model="dt" min-date="minDate" show-weeks="true" class="datepicker"></datepicker>
</div>
</div>
<div class="form-group">
<label for="fieldname" class="col-md-3 control-label">Amount Payable</label>
<div class="col-md-6">
<input name="amount_payable"
type="number"
placeholder="Numbers only"
required
ng-model="credentials.amount_payable"
class="form-control">
</div>
</div>
<div class="form-group">
<label for="fieldname" class="col-md-3 control-label">Total Collected</label>
<div class="col-md-6">
<input name="total_collected"
type="number"
placeholder="Numbers only"
required
ng-model="credentials.total_collected"
class="form-control">
</div>
</div>
<div class="form-group">
<label for="fieldname" class="col-md-3 control-label"></label>
<div class="col-md-6">
<input type="submit" class="finish btn-success btn" value="Submit" />
</div>
</div>
</form>
</panel>
<panel panel-class="panel-sky" heading="Fee Details">
<panel-controls>
<panel-control-collapse></panel-control-collapse>
</panel-controls>
<p ng-hide="isValid(feedetails)" class="ng-hide">No fee statements for the student.</p>
<div ng-show="isValid(feedetails)" class="table-responsive">
<table class="table">
<thead>
<tr>
<th style="padding-right:100px">Item Description</th>
<th>Due Date</th>
<th>Amount Payable</th>
<th>Total Collected</th>
<th>Outstanding</th>
<th>Fine</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in feedetails">
<td align="left"><i>{{item.description}}</i></td>
<td align="left"><i>{{item.duedate}}</i></td>
<td align="left"><i>{{item.amount_payable}}</i></td>
<td align="left"><i>{{item.total_collected}}</i></td>
<td align="left"><i>{{item.outstanding}}</i></td>
<td align="left"><i>{{item.fine}}</i></td>
</tr>
</tbody>
<form ng-controller="feeStatement"><input type="submit" class="finish btn-success btn" ng-click="test()" value="Submit" /></form>
</table>
</div>
</panel>
</div>
</div>
</div> <!-- container-fluid -->
This is my controller function:
$scope.submit = function(credentials) {
var outstanding = ($scope.credentials.amount_payable - $scope.credentials.total_collected);
var base_url = $("meta[name='base_url']").attr('content');
$scope.student_id = ($routeParams.student_id || "");
var data = {
'user_id': $scope.student_id,
'description': $scope.credentials.description,
'duedate': $scope.dt,
'amount_payable': $scope.credentials.amount_payable,
'total_collected': $scope.credentials.total_collected,
'outstanding': outstanding
};
$http({
method: 'post',
url: base_url + '/student/postfees',
data: data
}).
success(function(data, status, headers, config) {
if(data['success']) {
$scope.feedetails.push(data);
} else {
}
}).
error(function(data, status, headers, config) {
$('#error').html('code: ' + status);
$('#alert').fadeIn(1000).removeClass('hide');
});
};
When I submit a form $scope.feedetails updates, but the table data in rows still the same. But if i click on button with test() function which is within a table tag, the data updates dynamically.I've went through simillar topics, but that didn't helped. I assume that the problem with a $scope, can somebody give me a direction please.
PS. I've tried to put data in a rootScope, but still the same result.
The reason why:
Actually the issue is that $scope doesn't exist in success and you can neither try to inject from the function because in the code is happening this:
promise.success = function(fn) {
assertArgFn(fn, 'fn');
promise.then(function(response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
in particular note fn(response.data, response.status, response.headers, config); it means that is going to pass to your function only those arguments and there is not $scope or $rootScope at all in there.
How to fix the problem:
One thing you can do is generate a function that has access to $scope and inject it in .success.
One possible implementation is :
$scope.submit = function(credentials) {
var outstanding = ($scope.credentials.amount_payable - $scope.credentials.total_collected);
var base_url = $("meta[name='base_url']").attr('content');
$scope.student_id = ($routeParams.student_id || "");
var data = {
'user_id': $scope.student_id,
'description': $scope.credentials.description,
'duedate': $scope.dt,
'amount_payable': $scope.credentials.amount_payable,
'total_collected': $scope.credentials.total_collected,
'outstanding': outstanding
};
var callback = function(data) {
$scope.feedetails.push(data);
};
$http({
method: 'post',
url: base_url + '/student/postfees',
data: data
})
.success(function(data, status, headers, config) {
if(data['success']) {
callback(data);
} else {
}
})
.error(function(data, status, headers, config) {
$('#error').html('code: ' + status);
$('#alert').fadeIn(1000).removeClass('hide');
});
};