Dynamic textbox validation using ng-repeat - angularjs

I have following code which add dynamically textbox. The form contains Name and Programing skill textbox. The Programing skill textbox can be added dynamically.
I am trying to validate dynamic textbox. As of now it generates textbox every time when I click on "ADD" Button. If I entered anything in textbox then only it should be allowed to generate next textbox , else it should show a message/alert to fill the textbox.
I use ng-repeat to generate textbox.
<!DOCTYPE html>
<html>
<head>
<title>validation</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"></script>
</head>
<body>
<div ng-app="dynamicApp" ng-controller="dynamicController" class="container" style="width:600px;" ng-init="fetchData()">
<div class="alert alert-success alert-dismissible" ng-show="success" >
×
{{successMessage}}
</div>
<div class="alert alert-danger alert-dismissible" ng-show="error" >
×
{{errorMessage}}
</div>
<form method="post" ng-submit="submitForm()">
<div class="form-group">
<label>Enter Your Name</label>
<input type="text" name="name" id="name" ng-model="formData.person_name" class="form-control" />
</div>
<fieldset ng-repeat="row in rows">
<div class="form-group">
<label>Enter Your Programming Skill</label>
<div class="row">
<div class="col-md-9">
<input type="text" name="programming_languages[]" class="form-control" ng-model="formData.skill[$index + 1]" />
</div>
<div class="col-md-3">
<button type="button" name="remove" ng-model="row.remove" class="btn btn-danger btn-sm" ng-click="removeRow()"><span class="glyphicon glyphicon-minus"></span></button>
</div>
</div>
</div>
</fieldset>
<div class="form-group">
<button type="button" name="add_more" class="btn btn-success" ng-click="addRow()"><span class="glyphicon glyphicon-plus"></span> Add</button>
<input type="submit" name="submit" class="btn btn-info" value="Save" />
</div>
</form>
<div class="table-responsive">
<table class="table table-bordered table-striped">
<tr>
<th>Name</th>
<th>Programming Languages</th>
</tr>
<tr ng-repeat="name in namesData">
<td>{{name.name}}</td>
<td>{{name.programming_languages}}</td>
</tr>
</table>
</div>
</div>
</body>
</html>
<script>
var app = angular.module('dynamicApp', []);
app.controller('dynamicController', function($scope, $http){
$scope.success = false;
$scope.error = false;
$scope.fetchData = function(){
$http.get('/home/testdata').success(function(data){
$scope.namesData = data;
});
};
$scope.rows = [{name: 'programming_languages[]', name: 'remove'}];
$scope.addRow = function(){
var id = $scope.rows.length + 1;
$scope.rows.push({'id':'dynamic'+id});
};
$scope.removeRow = function(row){
var index = $scope.rows.indexOf(row);
$scope.rows.splice(index, 1);
};
$scope.formData = {};
$scope.submitForm = function(){
$http({
method:"POST",
url:"/home/test",
data:$scope.formData
}).success(function(data){
if(data.error != '')
{
$scope.success = false;
$scope.error = true;
$scope.errorMessage = data.error;
}
else
{
$scope.success = true;
$scope.error = false;
$scope.successMessage = data.message;
$scope.formData = {};
$scope.rows = [{name: 'programming_languages[]', name: 'remove'}];
$scope.fetchData();
}
});
};
});
</script>

Related

angular form ng-repeat deleting single form

i am working with dynamic forms with ng-repeat .i am getting dynamic forms according to my userid. each form has delete button. my requirement is once i am clicking delete button i need to delete that particular form and those values from my user obj and remaining values i need to send to server. in this example i want to delete id 2 (2nd form), and 1st and 2nd form data i need to store one variable.
please send some fiddle for this .
my html code
<div ng-app="myApp">
<div ng-controller="myCtrl">
<form role="form" name='userForm' novalidate>
<div class="container">
<div class="row" ng-repeat="user in users">
<div class="form-group">
<div class="col-md-3">
<label>ID</label>
<input ng-model="user.id" id="user.id" name="user.id" placeholder="Enter bugid" type="text" required readonly disabled>
</div>
<div class="col-md-3">
<label>Comments</label>
<textarea ng-model="user.comment" id="textarea1" rows="1" required></textarea>
</div>
<div class="col-md-3 ">
<label>Location</label>
<select ng-model="user.location" ng-options="v for v in locations" ng-init='initLocation(user)' name="select2" required>
</select>
</div>
<div>
<button>delete</button>
</div>
</div>
</div>
</div>
<div class="buttonContainer text-center btn-container">
<br>
<button ng-disabled="userForm.$invalid" type="button" id="adduser" ng-click="adduser()">Add user</button>
<button type="button" class="btn button--default btn--small pull-center">Close</button>
</div>
</form>
</div>
js file
var myApp = angular.module('myApp', []);
myApp.controller('myCtrl', function($scope, $timeout) {
$scope.ids = [1, 2, 3];
$scope.users = $scope.ids.map(function(id) {
return {
id: id,
comment: "",
location: ""
};
});
$scope.locations = ['india', 'usa', 'jermany', 'china', 'Dubai'];
$scope.initLocation = (user) => {
$timeout(() => {
user.location = $scope.locations[0];
});
}
$scope.adduser = function() {
var data = $scope.users.map(function(user) {
return {
"userid": user.id,
"manualcomment": user.comment,
"location": user.location
}
});
console.log("data", data)
}
});
As per your requirement i am adding ng-click to delete button and adding removeSelForm method and pass your user object into that function parameter. in controller i am removing that particular form values from users object.
var myApp = angular.module('myApp', []);
myApp.controller('myCtrl', function($scope, $timeout) {
$scope.ids = [1, 2, 3];
$scope.users = $scope.ids.map(function(id) {
return {
id: id,
comment: "",
location: ""
};
});
$scope.locations = ['india', 'usa', 'jermany', 'china', 'Dubai'];
$scope.initLocation = (user) => {
$timeout(() => {
user.location = $scope.locations[0];
});
}
$scope.removeSelForm = function(item) {
var index = $scope.users.indexOf(item)
$scope.users.splice(index, 1);
}
$scope.adduser = function() {
var data = $scope.users.map(function(user) {
return {
"userid": user.id,
"manualcomment": user.comment,
"location": user.location
}
});
console.log("data", data)
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="myApp">
<div ng-controller="myCtrl">
<form role="form" name='userForm' novalidate>
<div class="container">
<div class="row" ng-repeat="user in users">
<div class="form-group">
<div class="col-md-3">
<label>ID</label>
<input ng-model="user.id" id="user.id" name="user.id" placeholder="Enter bugid" type="text" required readonly disabled>
</div>
<div class="col-md-3">
<label>Comments</label>
<textarea ng-model="user.comment" id="textarea1" rows="1" required></textarea>
</div>
<div class="col-md-3 ">
<label>Location</label>
<select ng-model="user.location" ng-options="v for v in locations" ng-init='initLocation(user)' name="select2" required>
</select>
</div>
<div>
<button ng-click="removeSelForm(user)">delete</button>
</div>
</div>
</div>
</div>
<div class="buttonContainer text-center btn-container">
<br>
<button ng-disabled="userForm.$invalid" type="button" id="adduser" ng-click="adduser()">Add user</button>
<button type="button" class="btn button--default btn--small pull-center">Close</button>
</div>
</form>
</div>

Controller Value is not showing in view Angularjs

In the view {{phonenumber}} value is not updating. But When I enter digits alert is working properly inside the controller.
Controller
var app = angular.module('myApp', []);
app.controller('PosController', function ($scope, $http) {
$scope.phonenumberFromDial = "";
$scope.phonenumber = "";
$scope.updatePhoneNumber = function(id) {
$scope.phonenumberFromDial=id;
$scope.phonenumber =$scope.phonenumber+$scope.phonenumberFromDial;
if($scope.phonenumber.length > 9) {
console.log("Log phonenumber: " + $scope.phonenumberFromDial);
alert('Here the Number: '+ $scope.phonenumber);
}
});
View
<div ng-app="myApp" ng-controller="PosController" class="panel" >
<div class="input-group col-xs-4">
<div class="input-group-btn">
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#myModal">Telefono</button>
</div><!-- /btn-group -->
<div ng-app="myApp" ng-controller="PosController">
<input id="phonenumber" class="form-control" ng-model="phonenumber" />
<!--<input type="text" id="phonenumber" ng-model="myModel" ng-keyup="(myModel.length >= 3) && myFunction()" class="form-control" data-inputmask='"mask": "(999) 999-9999"' data-mask>-->
</div>
<div class="input-group-btn" >
<button type="button" class="btn btn-success">Cliente</button>
</div><!-- /btn-group -->
<div ng-app="myApp" ng-controller="PosController">\
<input type="text" id="cliente" class="form-control" value="{{phonenumber}}">
</div>
</div>
</div>
Some observations :
remove unecessary multiple ng-controller="PosController" and ng-app="myApp" from the code and leave with only one at the top.
use ng-model="phonenumber" instead of value="{{phonenumber}}" to perform two way data binding.
Working demo :
var app = angular.module('myApp', []);
app.controller('PosController', function ($scope, $http) {
$scope.phonenumberFromDial = "";
$scope.phonenumber = "";
$scope.updatePhoneNumber = function(id) {
$scope.phonenumberFromDial=id;
$scope.phonenumber =$scope.phonenumber+$scope.phonenumberFromDial;
if($scope.phonenumber.length > 9) {
console.log("Log phonenumber: " + $scope.phonenumberFromDial);
alert('Here the Number: '+ $scope.phonenumber);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="PosController" class="panel" >
<div class="input-group col-xs-4">
<input type="text" id="phonenumber" class="form-control" ng-model="phonenumber"/>
<div class="input-group-btn" >
<button type="button" class="btn btn-success" ng-click="updatePhoneNumber(phonenumber)">Cliente</button>
</div>
<input type="text" id="cliente" class="form-control" ng-model="phonenumber">
</div>
</div>
There are several things you're missing. First of the all, as suggested in comment, you only need to declare ng-app and ng-controller once in the HTML with np-app on the top-most level. Secondly, you bind the scope data to the HTML using ng-model inside a input field, or {{phonenumber}} in HTML. Third, you forgot to close the controller with an ending parenthesis.
Here is a working demo:
var app = angular.module('myApp', []);
app.controller('PosController', function ($scope, $http) {
$scope.phonenumberFromDial = "";
$scope.phonenumber = "";
$scope.updatePhoneNumber = function(id) {
$scope.phonenumberFromDial=id;
$scope.phonenumber =$scope.phonenumber+$scope.phonenumberFromDial;
if($scope.phonenumber.length > 9) {
console.log("Log phonenumber: " + $scope.phonenumberFromDial);
alert('Here the Number: '+ $scope.phonenumber);
}
}
});
<!doctype html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<script src="app.js"></script>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.0.4/css/bootstrap-combined.min.css">
</head>
<body>
<div class="panel" >
<div class="input-group col-xs-4" ng-controller="PosController">
<div class="input-group-btn">
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#myModal">Telefono</button>
</div><!-- /btn-group -->
<div>
<input id="phonenumber" class="form-control" ng-model="phonenumber" />
<!--<input type="text" id="phonenumber" ng-model="myModel" ng-keyup="(myModel.length >= 3) && myFunction()" class="form-control" data-inputmask='"mask": "(999) 999-9999"' data-mask>-->
</div>
<div class="input-group-btn" >
<button type="button" class="btn btn-success">Cliente</button>
</div><!-- /btn-group -->
<div>
<input type="text" id="cliente" class="form-control" ng-model="phonenumber">
</div>
<span>Phone#: {{phonenumber}}</span>
<div>
Dial: <input type="text" id="cliente" class="form-control" ng-model="phonenumberFromDial">
</div>
<div class="input-group-btn" >
<button type="button" class="btn btn-success" ng-click="updatePhoneNumber(phonenumberFromDial)">Update phone#</button>
</div><!-- /btn-group -->
</div>
</div>
</body>
</html>

Pass params between ng-click and a service Angular js

I have a "search" where the user input a value and i want to send this value in the service because i want that another controller can have access. But for the moment i can't do it, if someone can help me it would be very usfull i using Angular js.
And the js
var app = angular.module('MainApp', [])
app.factory('Search', function($rootScope, $http){
var search = '';
function setSearch(bus){
search = bus;
}
function getSearch(){
return search;
}
return{
setSearch : setSearch,
getSearch: getSearch
};
//return myFactory;
/*
$scope.Search = function() {
return {
getDoctor: function () {
return $http.get('api/doctor' + $scope.search.searchText).then(function (response) {
orders = response.data;
$rootScope.$broadcast('handleSharedOrders', orders);
return orders;
})
}
};
}*/
});
app.controller('mainController', function ($scope, $http, Search) {
$scope.loadList = function() {
location.href = "doctors";
};
$scope.search.searchText = Search.getSearch();
$scope.Search = function(bus) {
console.log(bus);
Search.setSearch(bus);
}
$scope.doctors = {};
$http.get('/api/doctor').success(function (data) {
$scope.doctors = data;
})
.error(function (data) {
console.log('Error: ' + data);
});
/*
$http.get('/api/doctor/' + specialty).success(function (data) {
$scope.doctorsSpecialty = data;
})
.error(function (data) {
console.log('Error: ' + data);
});
*/
});
<!DOCTYPE html>
<html ng-app="MainApp">
<head lang="en">
<meta charset="UTF-8">
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<!-- Cargamos app -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
<script src="../Controllers/core.js"></script>
<title></title>
</head>
<body ng-controller="mainController">
<div align="center">
<img src="../img/logo.jpg" >
</div>
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="login-panel panel panel-default" >
<div class="panel-heading" >
<h3 class="panel-title">Search Doctors</h3>
</div>
<div class="panel-body" >
<form role="form" >
<fieldset>
<div class="form-group" name="myForm" >
<input ng-model="search.searchText" type="text" class="form-control" placeholder="Search..." align="center">
</div>
<button class="btn btn-default" type="button" align="center" ng-click="Search(searchText)">
<b align="center">Search</b>
</button>
<!-- Change this to a button or input when using this as a form -->
</fieldset>
</form>
</div>
</div>
<div class="panel-heading" STYLE="background-color: #a7b5ce">
<h3 class="panel-title">List of Doctors</h3>
</div>
<div class="panel-body" >
<form role="form">
<fieldset>
<div class="form-group" name="myForm" >
<button class="btn btn-default" type="button" align="center" href=doctors ng-click="loadList()">
<b>List of Doctors</b>
</button>
</div>
<!-- Change this to a button or input when using this as a form -->
</fieldset>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
thank you for helping me
Here you have defined search.searchText:
<input ng-model="search.searchText" type="text" class="form-control" placeholder="Search..." align="center">
And here you are trying to pass just searchText (which is undefined):
<button class="btn btn-default" type="button" align="center" ng-click="Search(searchText)">
<b align="center">Search</b>
</button>
You need to either change your ng-model on your <input> to be 'search' or change the ng-click on your <button> to 'Search(search.searchText)'. If you choose to do the latter you may also want to explicitly create the search object in your controller.
I think you were doing it well, but your code has a few errors. First, you are not declaring the object search in your scope but you are assigning the property searchText to it. So you should do something like that:
$scope.search = {
searchText: ''
};
Then, in the view when you click search you are passing searchText but it should be search.searchText.
Have a look at this: https://jsfiddle.net/jruizx/54xcmgqp/

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

Resources