Updating data from controller to database in laravel - database

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...

Related

Edit methods not working Correctly

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;

submit button not working for AngularJS

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">

angularJS update table model on form submit

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');
});
};

SyntaxError: Unexpected token Y at Object.parse (native)

I am uploading a file using spring boot and angular js but when i click on import i have the erros mentioned in the title.
Here's my controller js
var app=angular.module("MyCat",[]);
app .directive("fileread", [function ()
{ return { scope: { fileread: "=" }, link: function (scope, element, attributes)
{ element.bind("change", function (changeEvent)
{ scope.$apply(function () { scope.fileread = changeEvent.target.files[0];
}); }); } } }]); // } }
//Upload files
$scope.upload=function(){
var fd = new FormData();
var url="http://localhost:8080/upload";
fd.append("file", $scope.rap.file);
fd.append("name",$scope.rap.name);
$http.post(url,fd,{
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
Here's my java controller
upload Files
#RequestMapping(value="/upload",headers=("content-type=multipart/*"),consumes = {"multipart/form-data"}, method=RequestMethod.POST)
public #ResponseBody String handleFileUpload(#RequestParam("name") String name,#RequestParam("file") MultipartFile file){
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
BufferedOutputStream stream =
new BufferedOutputStream(new FileOutputStream(new File(name)));
stream.write(bytes);
stream.close();
return "You successfully uploaded " + name + "!";
} catch (Exception e) {
return "You failed to upload " + name + " => " + e.getMessage();
}
} else {
return "You failed to upload " + name + " because the file was empty.";
}
}
Here's my html page
<section id="contact-page">
<div class="container">
<div class="center">
<p class="lead">Import reports</p>
</div>
<div class="row contact-wrap">
<div class="status alert alert-success" style="display: none"></div>
<form id="main-contact-form" class="contact-form" name="contact-form" method="POST" enctype="multipart/form-data" >
<div class="col-sm-5 col-sm-offset-1">
<div class="form-group">
<label>name *</label>
<input type="text" name="name" class="form-control" required="required" ng-model="rap.name">
</div>
<div class="form-group">
<label>DateOfUploade</label>
<input type="Date" class="form-control" ng-model="rap.dateOfUpload" >
</div>
<div class="form-group">
<label for="t">Type of File</label>
<select
class="form-control" id="t" ng-model="rap.type">
<option>.word</option>
<option>.xsl</option>
<option>.pdf</option>
</select>
</div>
<div class="form-group">
<label>file</label>
<input type="file" name="file" class="form-control" fileread="rap.file">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-lg" ng-click="upload()">Import File</button>
</div>
</div>
<table class="table">
<tr>
<th>NameOfUploader</th>
<th>DateOfUpload</th>
<th>TypeOfFile</th>
<th>File</th>
</tr>
<tr ng-repeat="rap in reports">
<td>{ {rap.NameOfUploader}}</td>
<td>{ {rap.DateOfUpload}}</td>
<td>{ {rap.TypeOfFile}}</td>
<td>{ {rap.File}}</td>
</tr>
</table>
</form>
</div><!--/.row-->
</div><!--/.container-->
</section><!--/#contact-page-->
enter code here
Any ideas ?
Unexpected token 'Y' - is starting of your message from java controller 'You successfully ...' that comes from the server instead of valid JSON string. Try to return something parseable: {"result": "You successfully bla-bla-bla..."}

how to establish a two-way binding between a text input and a parent scope model

In my Angular app, I have a view, which is presented as a tabbed UI, with multiple tabs created by default.
Each tab contains a number of Form elements, one of which is a text input named "tabName".
The purpose of each tab is to allow the user to upload an Excel file, and be able to describe the file contents using a few Form fields located on the same page.
All of the form elements in each tab are bound to a controller named "FileUploadController", but, the tab itself (specifically its name) is bound to a different controller, named "TabController".
I need to be able to have a two-way binding between the "tabName" text input in each tab, and the name property of the actual tab (which initially comes from "$scope.workspaces" within the TabController.
Currently, I am trying to handle this by creating a "activeWorkspaceSheetName" function within the TabController, and then referencing it as ng-model for the text input, but, it is not working.
Here are my files:
tabControl.html (the view):
<div class="container form-group">
<br>
<tabset>
<tab ng-repeat="workspace in workspaces"
heading="{{workspace.name}}"
active=workspace.active>
<div ng-controller="FileUploadController">
<hr>
<!--FILE UPLOAD CONTROL-->
<div class="container">
<div class="row">
<div class="col-md-3">
<input type="file" nv-file-select="" uploader="uploader" />
</div>
<div class="col-md-9" style="margin-bottom: 40px">
<h3>Upload queue</h3>
<p>Queue length: {{ uploader.queue.length }}</p>
<table class="table">
<thead>
<tr>
<th width="50%">Name</th>
<th ng-show="uploader.isHTML5">Size</th>
<th ng-show="uploader.isHTML5">Progress</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in uploader.queue">
<td><strong>{{ item.file.name }}</strong></td>
<td ng-show="uploader.isHTML5" nowrap>{{ item.file.size/1024/1024|number:2 }} MB</td>
<td ng-show="uploader.isHTML5">
<div class="progress" style="margin-bottom: 0;">
<div class="progress-bar" role="progressbar" ng-style="{ 'width': item.progress + '%' }"></div>
</div>
</td>
<td class="text-center">
<span ng-show="item.isSuccess"><i class="glyphicon glyphicon-ok"></i></span>
<span ng-show="item.isCancel"><i class="glyphicon glyphicon-ban-circle"></i></span>
<span ng-show="item.isError"><i class="glyphicon glyphicon-remove"></i></span>
</td>
<td nowrap>
<button type="button" class="btn btn-success btn-xs" ng-click="item.upload()" ng-disabled="item.isReady || item.isUploading || item.isSuccess">
<span class="glyphicon glyphicon-upload"></span> Upload
</button>
<button type="button" class="btn btn-warning btn-xs" ng-click="item.cancel()" ng-disabled="!item.isUploading">
<span class="glyphicon glyphicon-ban-circle"></span> Cancel
</button>
<button type="button" class="btn btn-danger btn-xs" ng-click="item.remove()">
<span class="glyphicon glyphicon-trash"></span> Remove
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<!--END OF FILE UPLOAD CONTROL-->
<div class="form-group">
<fieldset>
<legend><strong>Dataset Description</strong> </legend>
<div class="col-sm-6">
<label for="category">Category name</label>
<div id="category">
<isteven-multi-select
input-model="inputCategories"
output-model="outputCategories"
button-label="icon name"
item-label="icon name maker"
tick-property="ticked"
selection-mode="single"
>
</isteven-multi-select>
</div>
<label for="documentAuthor">Document author</label>
<input id="documentAuthor" name="documentAuthor" type="text" class="form-control" ng-model="documentAuthor"/>
<label for="dateDocumentRecieved">Date document recieved</label>
<input id="dateDocumentRecieved" name="dateDocumentRecieved" type="text" class="form-control" ng-model="dateDocumentReceived"/>
<label for="documentReviewer">Document reviewer</label>
<input id="documentReviewer" name="documentReviewer" type="text" class="form-control" ng-model="documentReviewer"/>
</div>
<div class="col-sm-6">
<label for="originalDocumentName">Original document name</label>
<input id="originalDocumentName" name="originalDocumentName" type="text" class="form-control" ng-model="originalDocumentName"/>
<label for="tabName">Sheet Name</label>
<input id="tabName" name="tabName" type="text" class="form-control" ng-model="$scope.$parent.activeWorkspaceSheetName"/>
<label for="dateDocumentProduced">Date document produced</label>
<input id="dateDocumentProduced" name="dateDocumentProduced" type="text" class="form-control" ng-model="dateDocumentProduced"/>
<label for="documentSubmitter">Document submitter</label>
<input id="documentSubmitter" name="documentSubmitter" type="text" class="form-control" ng-model="documentSubmitter"/>
</div>
</fieldset>
</div>
</div>
</tab>
<tab select="addWorkspace()">
<tab-heading> Add Sheet
<i class="icon-plus-sign"></i>
</tab-heading>
</tab>
<tab select="removeWorkspace()">
<tab-heading> Remove Selected Sheet
<i class="icon-plus-sign"></i>
</tab-heading>
</tab>
</tabset>
<br/>
<!--<button type="button" class="btn-primary" ng-click="collectValuesFromEachTab()">Submit Dataset</button>-->
<!--<h3>Workspaces</h3>-->
<!--<pre>{{workspaces|json}}</pre>-->
</div>
tabController.js:
angular.module('TabCtrl', ['ui.bootstrap'])
.controller("TabController", ['$scope','$http', function ($scope, $http) {
console.log("This is TabController");
var setAllInactive = function() {
angular.forEach($scope.workspaces, function(workspace) {
workspace.active = false;
});
};
$scope.activeWorkspaceSheetName = function(){
$scope.workspaces.forEach(function(workspace) {
if(workspace.active){
return workspace.name;
}
});
};
var addNewWorkspace = function() {
var id = $scope.workspaces.length + 1;
$scope.workspaces.push({
id: id,
name: "Sheet " + id,
active: true
});
};
$scope.workspaces =
[
{ id: 1, name: "Sheet 1" ,active:true },
{ id: 2, name: "Sheet 2" ,active:false }
];
$scope.addWorkspace = function () {
setAllInactive();
addNewWorkspace();
};
$scope.removeWorkspace = function() {
angular.forEach($scope.workspaces, function(workspace) {
if(workspace.active){
var index = $scope.workspaces.indexOf(workspace);
console.log('Active Workspace id: ' + index);
$scope.workspaces.splice(index,1);
}
})
};
}]);
fileUploadController.js:
angular.module('FileUploadCtrl', [])
.controller('FileUploadController', ['$scope', 'FileUploader', function($scope, FileUploader) {
console.log('This is File Upload Controller');
$scope.inputCategories = [
{
name: "Category 1"
},
{
name: "Category 2"
},
{
name: "Category 3"
}
];
var selectedCategory;
var uploader = $scope.uploader = new FileUploader({
url: 'http://10.211.55.25:8080/api/files',
tabName: 'sheet1'
});
// FILTERS
uploader.filters.push({
name: 'customFilter',
fn: function(item /*{File|FileLikeObject}*/, options) {
return this.queue.length < 10;
}
});
// CALLBACKS
uploader.onWhenAddingFileFailed = function(item /*{File|FileLikeObject}*/, filter, options) {
console.info('onWhenAddingFileFailed', item, filter, options);
};
uploader.onAfterAddingFile = function(fileItem) {
console.info('onAfterAddingFile', fileItem);
};
uploader.onAfterAddingAll = function(addedFileItems) {
console.info('onAfterAddingAll', addedFileItems);
};
uploader.onBeforeUploadItem = function(item) {
angular.forEach( $scope.outputCategories, function( value, key ) {
selectedCategory = value.name;
item.formData.push({subjectCategory: selectedCategory});
});
$scope.tabName = $scope.$parent.activeWorkspaceSheetName;
item.formData.push({tabName: $scope.tabName,
originalDocumentName: $scope.originalDocumentName,
subject: $scope.subject,
documentAuthor: $scope.documentAuthor,
dateDocumentProduced: $scope.dateDocumentProduced,
dateDocumentReceived: $scope.dateDocumentReceived,
documentSubmitter: $scope.documentSubmitter,
documentReviewer: $scope.documentReviewer,
dataFields: $scope.dataFields});
console.info('onBeforeUploadItem', item);
};
uploader.onProgressItem = function(fileItem, progress) {
console.info('onProgressItem', fileItem, progress);
};
uploader.onProgressAll = function(progress) {
console.info('onProgressAll', progress);
};
uploader.onSuccessItem = function(fileItem, response, status, headers) {
console.info('onSuccessItem', fileItem, response, status, headers);
};
uploader.onErrorItem = function(fileItem, response, status, headers) {
console.info('onErrorItem', fileItem, response, status, headers);
};
uploader.onCancelItem = function(fileItem, response, status, headers) {
console.info('onCancelItem', fileItem, response, status, headers);
};
uploader.onCompleteItem = function(fileItem, response, status, headers) {
console.info('onCompleteItem', fileItem, response, status, headers);
};
uploader.onCompleteAll = function() {
console.info('onCompleteAll');
};
console.info('uploader', uploader);
}]);
What is the proper way to have this two-way binding, so, when the user updates the tabName text input in each tab, the actual tab's name is also updated?
If I understood correctly you has an input tabName for each tab so you can try put this model in the tabName input:
<input id="tabName" name="tabName" type="text" class="form-control" ng-model="workspace.name"/>
Remember every time that angular can't find a property in a scope they look if exist in his parent, and if not exist they check in his parent parent and so on...

Resources