angularJS update table model on form submit - angularjs

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

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;

Updating data from controller to database in laravel

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

Passing results from Laravel 5.2 to view using AngularJS does not work correctly

I am learning how to intergrate Angular in my Laravel app. But when I select values from a database table its displayed in the browser in Json format like shown:
[{"id":1,"product_name":"smart phone"},
[{"id":2,"product_name":"laptop"},
[{"id":3,"product_name":"desktop"},
[{"id":4,"product_name":"tablet"}]
I want my result in the view to look as so:
id product Name
1 Smart Phone
2 Laptop
3 Desktop
4 tablet
My productsController.php listProducts()
//List all products
public function listProducts($id = null) {
if ($id == null) {
return Product::orderBy('id', 'asc')->get();
} else {
return $this->show($id);
}
}
My show products method:
public function show($id)
{
return Product::find($id);
}
my routes.php
Route::group(array('prefix' => 'api'), function() {
Route::get('/v1/products/{id?}' ,['as'=>'productindex','uses'=>'ProductsController#listProducts']);
Route::post('/v1/products', 'ProductsController#store');
Route::post('/v1/products/{id}', 'ProductsController#update');
Route::post('/v1/products/update/{id}',['as'=>'update','uses'=> 'ProductsController#update']);
Route::delete('/v1/products/{id}', 'ProductsController#destroy');
});
My productsController.js
//public/app/controllers/productsController.js
app.controller('productsController', function($scope, $http, API_URL) {
//retrieve products listing from API
$http.get(API_URL + "products")
.success(function(response) {
$scope.products = response;
});
//show modal form
$scope.toggle = function(modalstate, id) {
$scope.modalstate = modalstate;
switch (modalstate) {
case 'add':
$scope.form_title = "Add New Product";
break;
case 'edit':
$scope.form_title = "Product Detail";
$scope.id = id;
$http.get(API_URL + 'products/' + id)
.success(function(response) {
console.log(response);
$scope.product = response;
});
break;
default:
break;
}
console.log(id);
$('#myModal').modal('show');
}
//save new record / update existing record
$scope.save = function(modalstate, id) {
var url = API_URL + "products";
//append employee id to the URL if the form is in edit mode
if (modalstate === 'edit'){
url += "/" + id;
}
$http({
method: 'POST',
url: url,
data: $.param($scope.Product),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(response) {
console.log(response);
location.reload();
}).error(function(response) {
console.log(response);
alert('This is embarassing. An error has occured. Please check the log for details');
});
}
//delete record
$scope.confirmDelete = function(id) {
var isConfirmDelete = confirm('Are you sure you want this record?');
if (isConfirmDelete) {
$http({
method: 'DELETE',
url: API_URL + 'products/' + id
}).
success(function(data) {
console.log(data);
location.reload();
}).
error(function(data) {
console.log(data);
alert('Unable to delete');
});
} else {
return false;
}
}
});
My app.js
//public/app/app.js
var app = angular.module('products', [])
.constant('API_URL', 'http://localhost/myapp/public/api/v1/');
my view
// resources/views/products/listproducts.php
<!DOCTYPE html>
<html lang="en-US" ng-app="products">
<head>
<title>Laravel 5 AngularJS CRUD Example</title>
<!-- Load Bootstrap CSS -->
<link href="<?= asset('css/bootstrap.min.css') ?>" rel="stylesheet">
</head>
<body>
<h2>Employees Database</h2>
<div ng-controller="productsController">
<!-- Table-to-load-the-data Part -->
<table class="table">
<thead>
<tr>
<th>Product Id</th>
<th>Product Name</th>
<th><button id="btn-add" class="btn btn-primary btn-xs" ng-click="toggle('add', 0)">Add New Product</button></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="product in products">
<td>{{ product.proudct_id }}</td>
<td>{{ product.product_name }}</td>
<td>
<button class="btn btn-default btn-xs btn-detail" ng-click="toggle('edit', product.id)">Edit</button>
<button class="btn btn-danger btn-xs btn-delete" ng-click="confirmDelete(product.id)">Delete</button>
</td>
</tr>
</tbody>
</table>
<!-- End of Table-to-load-the-data Part -->
<!-- Modal (Pop up when detail button clicked) -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">{{form_title}}</h4>
</div>
<div class="modal-body">
<form name="frmEmployees" class="form-horizontal" novalidate="">
<div class="form-group error">
<label for="inputEmail3" class="col-sm-3 control-label">Name</label>
<div class="col-sm-9">
<input type="text" class="form-control has-error" id="name" name="name" placeholder="Fullname" value="{{name}}"
ng-model="employee.name" ng-required="true">
<span class="help-inline"
ng-show="frmEmployees.name.$invalid && frmEmployees.name.$touched">Name field is required</span>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label">Email</label>
<div class="col-sm-9">
<input type="email" class="form-control" id="email" name="email" placeholder="Email Address" value="{{email}}"
ng-model="employee.email" ng-required="true">
<span class="help-inline"
ng-show="frmEmployees.email.$invalid && frmEmployees.email.$touched">Valid Email field is required</span>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label">Contact Number</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="contact_number" name="contact_number" placeholder="Contact Number" value="{{contact_number}}"
ng-model="employee.contact_number" ng-required="true">
<span class="help-inline"
ng-show="frmEmployees.contact_number.$invalid && frmEmployees.contact_number.$touched">Contact number field is required</span>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label">Position</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="position" name="position" placeholder="Position" value="{{position}}"
ng-model="employee.position" ng-required="true">
<span class="help-inline"
ng-show="frmEmployees.position.$invalid && frmEmployees.position.$touched">Position field is required</span>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="btn-save" ng-click="save(modalstate, id)" ng-disabled="frmEmployees.$invalid">Save changes</button>
</div>
</div>
</div>
</div>
</div>
<!-- Load Javascript Libraries (AngularJS, JQuery, Bootstrap) -->
<script src="<?= asset('app/lib/angular/angular.min.js') ?>"></script>
<script src="<?= asset('js/jquery.min.js') ?>"></script>
<script src="<?= asset('js/bootstrap.min.js') ?>"></script>
<!-- AngularJS Application Scripts -->
<script src="<?= asset('app/app.js') ?>"></script>
<script src="<?= asset('app/controllers/productsController.js') ?>"></script>
</body>
</html>
My question is what May I doing wrong. Its like the listProducts method in productsController.php is not passing results to listproducts.php. What should I do? Kindly assist.
Laravel and angular notations overlap (both blade and angular use '{{' to output variables). I had to change angular behaviour using:
app.config(['$interpolateProvider',
function($interpolateProvider) {
$interpolateProvider.startSymbol('[[');
$interpolateProvider.endSymbol(']]');
}])
I guess you can do something similar on Laravel, but I don't know how.
that problem solved, you could try and output the content of '$scope.products' in the html page, to see if it is what you expect. The response to the api call seems ok, so the problem likely lies in the angular side.

Form Submission in Modal Window and Refresh Content of a Tab

I have 2 tabs: list.brands and add.brand:
<script type="text/ng-template" id="list.brands">
<table class="table table-striped table-bordered bootstrap-datatable datatable dataTable" id="DataTables_Table_0" aria-describedby="DataTables_Table_0_info" ng-controller="BrandsCtrl">
<input type="text" ng-model="searchBox">
<thead>
<tr>
<th><tags:label text="brandid"/></th>
<th><tags:label text="name"/></th>
<th><tags:label text="isactive"/></th>
<th></th>
</tr>
</thead>
<tbody>
<tr id="actionresult{{$index + 1}}" ng-repeat="brand in brands | filter:searchBox">
<td>{{brand.brandid}}</td>
<td>{{brand.name}}</td>
<td>{{brand.isactive}}</td>
<td>
<a class="btn btn-ext-darkblue btn-ext-darkblue savestockbtn" ng-click="open(brand.brandid)"><tags:label text="edit"/></a>
<a class="btn btn-ext-darkblue btn-modal-trigger btn-ext-darkblue savestockbtn" href="/admin.brands/deleteConfirm?brandid={{brand.brandid}}" data-toggle="modal" ><tags:label text="delete"/></a>
</td>
</tr>
</tbody>
</table>
</script>
<script type="text/ng-template" id="add.brand">
<div class="row-fluid sortable">
<div class="box span12">
<div class="box-content">
<form class="form-horizontal" action='/admin.brands/add' data-toggle="modalform" data-popup="modal" name="brandform">
<div class="section-heading"></div>
<div class="control-group">
<label class="control-label" for="selectError"><tags:label text="name"/> *</label>
<div class="controls">
<input name="name" required/>
<span ng-show="brandform.name.$error.required"> Name is required. </span>
</div>
</div>
<div class="control-group">
<label class="control-label" for="selectError"><tags:label text="isactive"/> </label>
<div class="controls">
<input type="checkbox" name="isactive" value="1">
</div>
</div>
<div class="section-heading"><tags:label text="logo"/></div>
<div class="control-group">
<label class="control-label" for="textarea2"></label>
<div class="controls">
<template:file.upload dropzoneWidth="200px" dropzoneHeight="160px" maxFiles="1"></template:file.upload>
</div>
</div>
<div class="form-actions">
<tags:label text="close"/>
<button ng-disabled="brandform.name.$invalid" type="submit" class="btn btn-ext-lightblue"><tags:label text="save"/></button>
</div>
</form>
</div>
</div>
</div>
</script>
I switch them with
<div class="content-header">
<div class="row">
<div class="content-name span4">
<h3><i class="glyphicon glyphicon-bold"></i><tags:label text="brands"/></h3>
</div>
<div class="span8 button-group">
<jsp:include page="/admin/jsp/screens/help-button-inc.jsp"></jsp:include>
</div>
</div>
</div>
<div ng-app="myApp" ng-controller="TabsCtrl">
<div id="tabs" >
<ul class="nav nav-tabs content-tab-header" id="content_tab_0">
<li ng-repeat="tab in tabs" ng-class="{active:isActiveTab(tab.url)}" ng-click="onClickTab(tab)"><a><i class="{{tab.cssClass}}"></i><tags:label text="{{tab.title}}"/></a></li>
</ul>
</div>
<div id="mainView">
<div ng-include="currentTab"></div>
</div>
At list, I can open a modal window that contains brand details by clicking edit button in list.brands. My modal window:
<div class="row-fluid sortable">
<div class="box span12">
<div class="box-content">
<form class="form-horizontal" name="brandform" action='/admin.brands/update' data-toggle="validate" method="post">
<fields:form formName="brand.id.form">
<input type="hidden" name="brandid" value="{{item.brandid}}"/>
</fields:form>
<fields:form formName="brand.form">
<div class="section-heading"></div>
<div class="control-group">
<label class="control-label" for="selectError"><tags:label text="name"/> *</label>
<div class="controls">
<input name="name" value="{{item.name}}" required/>
</div>
</div>
<div class="control-group">
<label class="control-label" for="selectError"><tags:label text="isactive"/> </label>
<div class="controls">
<input type="checkbox" ng-checked="item.isactive" name="isactive" value="1"/>
</div>
</div>
</fields:form>
<div class="form-actions">
<a ng-click="cancel()" class="btn btn-ext-lightblue"><tags:label text="close"/></a>
<a ng-click="ok()" class="btn btn-ext-darkblue btn-disable-on-submit" ><tags:label text="save"/></a>
</div>
</form>
</div>
</div>
</div>
and my app is here:
<script>
var app = angular.module('myApp', ['ui.bootstrap']);
app.controller("BrandsCtrl", function($scope, $http, $controller) {
$http.get('/admin.brands/getJSONDataOfSearch').
success(function(data, status, headers, config) {
$scope.brands = data;
}).
error(function(data, status, headers, config) {
});
angular.extend(this, $controller("BrandCtrl", {$scope: $scope}));
});
app.controller("BrandCtrl", function ($scope, $http, $modal) {
$scope.animationsEnabled = true;
$scope.open = function (id) {
var modalInstance = $modal.open({
animation: $scope.animationsEnabled,
templateUrl: '/admin.brands/edit',
controller:gg,
resolve: {
item: function($http) {
return $http.get('/admin.brands/getJsonBrandAndEdit?brandid=' + id)
.then(function(response) {
return response.data;
});
}
}
});
}
});
var gg = function ($scope, $modalInstance, item) {
$scope.item = item;
$scope.ok = function () {
$scope.form.brandform.submit();
$modalInstance.close();
};
$scope.cancel = function () {
$modalInstance.dismiss();
};
}
app.controller('TabsCtrl', ['$scope', function ($scope) {
$scope.tabs = [{
title: 'list.brands',
url: 'list.brands',
cssClass: 'icon-th-list'
}, {
title: 'add.brand',
url: 'add.brand',
cssClass: 'icon-plus'
}];
$scope.currentTab = 'list.brands';
$scope.onClickTab = function (tab) {
$scope.currentTab = tab.url;
}
$scope.isActiveTab = function(tabUrl) {
return tabUrl == $scope.currentTab;
}
}]);
</script>
My questions is; how can I submit my edit form in modal to a target URL and refresh the list of brands.
in angular, form has a in-built event called ng-submit. You can submit the form in either way via submit button or using enter key. on ng-submit event, you need to pass a function which must be written within your controller. in that controller you can do what ever you want to do. To use a service, go through the documentation.
Here I am attaching an working example of Form Submit with Service integrated in it (Just for your reference, I have added 2 different controllers which are sharing the same service):
Fiddle: http://jsfiddle.net/ashishanexpert/zvcx5z38/2/
I think this could help you. Thanks
$scope.open = function (id) {
var modalInstance = $modal.open({
animation: $scope.animationsEnabled,
templateUrl: '/admin.brands/edit',
controller:gg,
resolve: {
item: function($http) {
return $http.get('/admin.brands/getJsonBrandAndEdit?brandid=' + id)
.then(function(response) {
return response.data;
});
}
}
});
modalInstance.result.then(function (item) {
//The function that load your data in this controller
LoadData();
})
}

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