I cannot save data from angular to backend laravel database - javascript

I am passing form input from angular to laravel view api. But data cannot be saved in the database. I am getting the following error messages in the console:
error: [ngRepeat:dupes] http://errors.angularjs.org/1.5.0/ngRepeat/dupes?p0=app%20in%20apps&p1=string%3A%3C&p2=%3C
at Error (native)
at http://localhost/myapp/public/app/lib/angular-1.5.0/angular.min.js:6:416
at http://localhost/myapp/public/app/lib/angular-1.5.0/angular.min.js:292:254
at http://localhost/myapp/public/app/lib/angular-1.5.0/angular.min.js:137:302
at m.$digest (http://localhost/myapp/public/app/lib/angular-1.5.0/angular.min.js:138:399)
at m.$apply (http://localhost/myapp/public/app/lib/angular-1.5.0/angular.min.js:141:341)
at g (http://localhost/myapp/public/app/lib/angular-1.5.0/angular.min.js:94:139)
at t (http://localhost/myapp/public/app/lib/angular-1.5.0/angular.min.js:98:260)
at XMLHttpRequest.u.onload (http://localhost/myapp/public/app/lib/angular-1.5.0/angular.min.js:99:297)(anonymous function) # angular.js:13236
apps.js:28 0
http://localhost/myapp/public/api/apps Failed to load resource: the server responded with a status of 500 (Internal Server Error)
I also get laravel errors:
<span class="exception_title"><abbr title="Illuminate\Database\QueryException">QueryException</abbr> in <a title="C:\xampp\htdocs\dukamart\vendor\laravel\framework\src\Illuminate\Database\Connection.php line 651" ondblclick="var f=this.innerHTML;this.innerHTML=this.title;this.title=f;">Connection.php line 651</a>:</span>
span class="exception_message">SQLSTATE[23000]: Integrity constraint violation: 1048 Column associated with input values.
I have checked my laravel controller seem to be fine. I am posting data from a popup form.
employeeController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Employee;
class Employees extends Controller
{
//
public function index($id = null) {
if ($id == null) {
return Employee::orderBy('id', 'asc')->get();
} else {
return $this->show($id);
}
}
public function store(Request $request) {
$employee = new Employee;
$employee->name = $request->input('name');
$employee->email = $request->input('email');
$employee->contact_number = $request->input('contact_number');
$employee->position = $request->input('position');
$employee->save();
return 'Employee record successfully created with id ' . $employee->id;
}
//My angular controller
app.controller('employeesController', function($scope, $http, API_URL) {
//retrieve employees listing from API
$http.get(API_URL + "employees")
.success(function(response) {
$scope.employees = response;
});
//show modal form
$scope.toggle = function(modalstate, id) {
$scope.modalstate = modalstate;
switch (modalstate) {
case 'add':
$scope.form_title = "Add New Employee";
break;
case 'edit':
$scope.form_title = "Employee Detail";
$scope.id = id;
$http.get(API_URL + 'employees/' + id)
.success(function(response) {
console.log(response);
$scope.employee = 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 + "employees";
//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.employee),
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 + 'employees/' + id
}).
success(function(data) {
console.log(data);
location.reload();
}).
error(function(data) {
console.log(data);
alert('Unable to delete');
});
} else {
return false;
}
}
});
When I click to save the data, I am getting an error message I had setup in employeeController.js controller
$http({
method: 'POST',
url: url,
data: $.param($scope.hotel),
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');
});
}
This my app.js
var app = angular.module(employees, [])
.constant('API_URL', 'http://localhost/myapp/public/api/');
My routes.php
Route::get('/api/v1/employees/{id?}', 'Employees#index');
Route::post('/api/v1/employees', 'Employees#store');
Route::post('/api/v1/employees/{id}', 'Employees#update');
Route::post('/api/v1/employees/update/{id}',['as'=>'update','uses'=> 'Employees#update']);
Route::delete('/api/v1/employees/{id}', 'Employees#destroy');
What could be the cause of this? Please help. I have tried to solve this for 3 days without success.
My View in resources/views/employees/employee.php
<!DOCTYPE html>
<html lang="en-US" ng-app="employeeRecords">
<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="employeesController">
<!-- Table-to-load-the-data Part -->
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Contact No</th>
<th>Position</th>
<th><button id="btn-add" class="btn btn-primary btn-xs" ng-click="toggle('add', 0)">Add New Employee</button></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="employee in employees">
<td>{{ employee.id }}</td>
<td>{{ employee.name }}</td>
<td>{{ employee.email }}</td>
<td>{{ employee.contact_number }}</td>
<td>{{ employee.position }}</td>
<td>
<button class="btn btn-default btn-xs btn-detail" ng-click="toggle('edit', employee.id)">Edit</button>
<button class="btn btn-danger btn-xs btn-delete" ng-click="confirmDelete(employee.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/employees.js') ?>"></script>
</body>
</html>

sound like your key is being duplicate in ng-repeat. Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: app in apps, Duplicate key: string:<, Duplicate value: <
this issue happens once
Invalid:
ng-repeat="value in [4, 4]"
valid
ng-repeat="value in [4, 4] track by $index"

In your app.js file.
Change the first line to:
var app = angular.module('employees', ['ngRoute'])

Related

Laravel 7 dynamic "add fields" form. foreach() argument must be of type array|object, null given

This my first post here, but by no mean my first time visiting. I'm an amateur coder and I'm working on something that has stumped me for passed day or two...
I'm building a site using Laravel 7. One of the pages includes a dynamic form that allows the user to add addition for fields as needed.
I'm am generating the dynamic form fields and a tinymce editor as well as submitting the form using javascript.
The issue I'm running into is this:
Upon clicking the 'Submit' button the page does not transition or show any signs of having been submitted. The first portion of the form data is successfully submitted and added to the appropriate database table but the dynamic fields are not added to their table and an error is thrown in the browser console.
The believe the relevant issue is message "foreach() argument must be of type array|object, string given" as this seems to be where the code stops running and things go wrong.
This function applies to the dynamic image_id[] portion of the form.
The full error info is:
XHR POST https://www.mydomainname.com/create
[HTTP/1.1 500 Internal Server Error 479ms]
Request:
format "galleries"
title "This+is+the+title+of+the+content"
short "This+is+the+short+description+for+the+content."
thumb "https://www.mydomainname.com/storage/giraffe1.jpg"
category "funny"
image_id […]
0 "Image+1"
1 "Image+2"
2 "Image+3"
Response:
message "foreach() argument must be of type array|object, string given"
exception "ErrorException"
file "/home/user/site/app/Http/Controllers/ContentController.php"
line 149
trace [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, … ]
Line 149:
foreach($request->input('image_id[]') as $key => $image) {
This is my Blade View, including the Javascript:
#extends('layouts.app')
#section('title', 'Post New Content')
#section('content')
<script src="https://cdn.tiny.cloud/1/arx09ivbx1ikchqgcvc6558h9sx2crokpd2c1152g667mh0c/tinymce/6/tinymce.min.js"></script>
<script src="/vendor/laravel-filemanager/js/stand-alone-button.js"></script>
<div class="container">
<div class="row">
<div class="col-md-8">
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
<div class="alert alert-danger print-error-msg" style="display:none">
<ul></ul>
</div>
<div class="alert alert-success print-success-msg" style="display:none">
<ul></ul>
</div>
<div class="card shadow">
<h2 class="card-header">
Post a New Gallery
<a class="btn btn-danger" style="float: right" href="{{ url()->previous() }}" onclick="return confirm('Are you sure? All progress will be lost!')">Go Back</a>
</h2>
<div class="card-body">
<form name="add_name" id="add_name">
<input type="hidden" name="format" value="galleries" class="form-control" required>
<div class="form-group row mb-0">
<div class="col-md-12">
<strong>Title:</strong>
<input type="text" name="title" class="form-control" required>
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-12">
<strong>Description:</strong>
<input type="text" name="short" class="form-control" required>
</div>
</div>
<div class="col-md-12">
<div class="row">
<div class="col-md-6">
<strong>Thumbnail:</strong>
<div class="input-group">
<div class="col-md-10">
<input type="text" id="thumb" class="form-control" name="thumb" aria-label="thumb" aria-describedby="button-image" required>
</div>
<div class="col-md-2">
<div class="input-group-append">
<button class="btn btn-primary" type="button" id="button-image">Browse</button>
</div>
</div>
</div>
</div>
<div class="col-md-6">
<strong>Category: </strong>
<select name="category" class="form-control" required>
<option value="" disabled selected>Select content category...</option>
#foreach($allCategories as $category)
<option value="{{ $category->name }}">{{ ucfirst(trans($category->name)) }}</option>
#endforeach
</select>
</div>
</div>
</div>
<br>
<!-- Dynamic Fields -->
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr>
<td><input type="text" name="image_id[]" class="form-control name_list" /></td>
<td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
</tr>
</table>
<input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />
</div>
<!-- End Dynamic Fields -->
</form>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
var postURL = "<?php echo url('create'); ?>";
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'" class="dynamic-added">' +
'<td><input type="text" name="image_id[]" class="form-control name_list" /></td>' +
'<td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td>' +
'</tr>');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#submit').click(function(){
$.ajax({
url:postURL,
method:"POST",
data:$('#add_name').serialize(),
type:'json',
success:function(data)
{
if(data.error){
printErrorMsg(data.error);
}else{
i=1;
$('.dynamic-added').remove();
$('#add_name')[0].reset();
$(".print-success-msg").find("ul").html('');
$(".print-success-msg").css('display','block');
$(".print-error-msg").css('display','none');
$(".print-success-msg").find("ul").append('<li>Record Inserted Successfully.</li>');
}
}
});
});
function printErrorMsg (msg) {
$(".print-error-msg").find("ul").html('');
$(".print-error-msg").css('display','block');
$(".print-success-msg").css('display','none');
$.each( msg, function( key, value ) {
$(".print-error-msg").find("ul").append('<li>'+value+'</li>');
});
}
});
</script>
<script>
document.addEventListener("DOMContentLoaded", function() {
document.getElementById('button-image').addEventListener('click', (event) => {
event.preventDefault();
window.open('/file-manager/fm-button', 'fm', 'width=1400,height=800');
});
});
// set file link
function fmSetLink($url) {
document.getElementById('thumb').value = $url;
}
</script>
#endsection
And here is my Controller:
public function createPost(Request $request)
{
$post = new Content();
$post->title = $request->get('title');
$post->short = $request->get('short');
$post->long = $request->get('long');
$post->thumb = $request->get('thumb');
$post->format = $request->get('format');
$post->category = $request->get('category');
$post->author = Auth::user()->id;
$post->save();
$order = 0;
foreach($request->input('image_id[]') as $key => $content) {
$contentImg = new ContentImages();
$contentImg->content_id = $post->id;
$contentImg->image_id = $content->image_id;
$contentImg->image_order = $order+1;
$contentImg->save();
}
return response()->json(['success'=>'done']);
}
And, finally, my Routes:
Route::get("create","ContentController#create");
Route::post("create","ContentController#createPost");
Things I Have Tried
I've tried several variations of the image_id syntax and nothing seems to be working...
As posted above:
foreach() argument must be of type array|object, null given
Using $request->input('image_id'):
"Attempt to read property \"image_id\" on string"
I tried $request('image_id') and got:
Object of type Illuminate\Http\Request is not callable
Then I tried $request->input(['image_id']) which just gave
foreach() argument must be of type array|object, null given
The output from dd($request->input('image_id') is:
array:2 [
0 => "Name 1"
1 => "Name 2"
]
and dd($request->input('image_id[]')) gave null.
Output of dd($request->all()):
array:6 [
"format" => "galleries"
"title" => "Thoughtless Driver Ruins Everyone's Day at the Wildlife Park"
"short" => "This lady made a mess at the West Midland Safari Park. The Giraffe was not injured."
"thumb" => "https://www.mydomainname.com/storage/photos/1/6317a2b460c98.jpg"
"category" => "oops"
"image_id" => array:3 [
0 => "Name 1"
1 => "Name 2"
2 => "Name 3"
]
]
I'm really lost on this one.
Any guidance here would be GREATLY appreciated, as well as any recommendations on better ways to handle this scenario.
I'm a marginally talented amateur with this stuff but nowhere near expert and I'm always looking to learn.
Much thanks in advance!!
SMR
Okay, so I figured out what I was doing wrong.
$request->input('image_id') was the correct solution.
My issue was further down. Once I corrected to $request->input('image_id'), this lead to another error, "Attempt to read property \"image_id\" on string", but this was actually due to a syntax error further down the page.
Fixed that, and all is now well!
Thank you to those who helped!

Load DataTable data to a Edit Modal

I am trying to create an edit function for my data table. The data table is created using Yajra Data tables. Everything working fine unless when I try to load existing data into the edit modal it fails. No error is showing but the modal does not launch. I have only included a little portion of my code here for easy reference.
Modal:
<!-- Update Status Model Box -->
<div id="updateStatusModal" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content bg-default">
<div class="modal-body">
<form class="form-horizontal" id="updateStatus">
#csrf
#method('PUT')
<div class="row">
<div class="col">
<div class="form-group text-center">
<h6 class="font-weight-bold">Stage 1</h6>
<label for="stage_1" class="switch">
<input type="checkbox" class="form-control" id="stage_1">
<div class="slider round"></div>
</label>
</div>
</div>
</div>
<div class="row">
<div class="col">
<div class="form-group">
<div class="col-md">
<label for="firstname">Coding</label>
<input type="text" class="form-control" id="first_name" value="" placeholder="Enter Completed Page Count">
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer justify-content-between">
<button type="button" name="update_btn" id="update_btn" class="btn btn-outline-warning">Update</button>
</div>
</div>
</div>
</div>
jquery funtion:
// Edit action
$(document).on('click', '.updateStatus', function(){
$tr = $(this).closest('tr');
var data = $tr.clidren("td").map(function(){
return $(this).text();
}).get();
console.log(data);
$('#id').val(data[0]);
$('#job_id').val(data[2]);
$('#stage_1').val(data[3]);
$('#conversion').val(data[4]);
$('#updateStatusModal').modal('show');
});
I tried this method I found but this is not working. Can anyone provide me any pointers here?
I've just didn't seen your front scripts (also back-end codes), but instead I can share my implementation for that you need. It works perfectly like showed in this (screenshot).
Here I'll put front and back codes. There is functionality for editing existsing Datatable record, also record deletion.
FRONT
<!--HERE ATTACH NECESSARY STYLES-->
<!--VIEW end-->
<link rel="stylesheet" type="text/css" href="{{ asset('css/admin/datatables.min.css') }}"/>
<table id="yajra_datatable" class="table table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Options</th>
</tr>
</thead>
</table>
<div class="modal modal-danger fade" id="modal_delete">
<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">Delete Language</h4>
</div>
<div class="modal-body">
<p>Are You sure You want to delete this Language?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline pull-left" data-dismiss="modal">Cancel</button>
<button id="delete_action" type="button" class="btn btn-outline">Submit</button>
</div>
</div>
</div>
</div>
<div class="modal modal-warning fade" id="modal_edit">
<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">Edit Language</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="language_name">Language Name</label>
<input name="language_name" id="language_name" type="text" value="" class="form-control" placeholder="Language Name">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline pull-left" data-dismiss="modal">Cancel</button>
<button id="edit_action" type="button" class="btn btn-outline">Submit</button>
</div>
</div>
</div>
</div>
<input type="hidden" id="item_id" value="0" />
<!--VIEW end-->
<!--HERE ATTACH NECESSARY SCRIPTS-->
<!--SCRIPTS start-->
<script src="{{ asset('js/admin/jquery.dataTables.min.js') }}"></script>
<script type="text/javascript">
var YajraDataTable;
function delete_action(item_id){
$('#item_id').val(item_id);
}
function edit_action(this_el, item_id){
$('#item_id').val(item_id);
var tr_el = this_el.closest('tr');
var row = YajraDataTable.row(tr_el);
var row_data = row.data();
$('#language_name').val(row_data.name);
}
function initDataTable() {
YajraDataTable = $('#yajra_datatable').DataTable({
"processing": true,
"serverSide": true,
"ajax": "{{ route('admin.book_languages.ajax') }}",
"columns":[
{
"data": "name",
"name": "name",
},
{
"data": "",
"name": ""
},
],
"autoWidth": false,
'columnDefs': [
{
'targets': -1,
'defaultContent': '-',
'searchable': false,
'orderable': false,
'width': '10%',
'className': 'dt-body-center',
'render': function (data, type, full_row, meta){
return '<div style="display:block">' +
'<button onclick="delete_action(' + full_row.id + ')" type="button" class="delete_action btn btn-danger btn-xs" data-toggle="modal" data-target="#modal_delete" style="margin:3px"><i class="fa fa-remove"></i> Delete</button>' +
'<button onclick="edit_action(this, ' + full_row.id + ')" type="button" class="edit_action btn btn-warning btn-xs" data-toggle="modal" data-target="#modal_edit" style="margin:3px"><i class="fa fa-edit"></i> Edit</button>' +
'</div>';
}
}
],
});
return YajraDataTable;
}
$(document).ready(function() {
var YajraDataTable = initDataTable();
$('#delete_action').on('click', function (e) {
e.preventDefault();
$.ajax({
url: "{{ route('admin.book_languages.delete') }}",
data: {
'item_id': $('#item_id').val(),
'_token': "{{ csrf_token() }}"
},
type: "POST",
success: function (data) {
$('#modal_delete').modal('hide');
YajraDataTable.ajax.reload(null, false);
console.log(data.message);
}
})
});
$('#edit_action').on('click', function (e) {
e.preventDefault();
$.ajax({
url: "{{ route('admin.book_languages.edit') }}",
data: {
'item_id': $('#item_id').val(),
'language_name': $('#language_name').val(),
'_token': "{{ csrf_token() }}"
},
type: "POST",
success: function (response) {
$('#modal_edit').modal('hide');
YajraDataTable.ajax.reload(null, false);
console.log(data.message);
}
})
});
$('#modal_delete').on('hidden.bs.modal', function () {
$('#item_id').val(0);
});
$('#modal_edit').on('hidden.bs.modal', function () {
$('#item_id').val(0);
$('#language_name').val("");
});
});
</script>
<!--SCRIPTS end-->
BACK
public function index() {
return view('admin.book-languages.index');
}
public function ajax() {
$items = BookLanguage::latest('id');
return DataTables::of($items)->make(true);
}
public function delete(Request $request) {
$item_id = $request->get('item_id');
$item = BookLanguage::find($item_id);
if(empty($item)) {
return response()->json([
'success' => false,
'message' => 'Item not found!',
], 200); // 404
} else {
$item->delete();
return response()->json([
'success' => true,
'message' => 'Item successfully deleted.',
], 200);
}
}
public function update(Request $request) {
$item_id = $request->get('item_id');
$item = BookLanguage::find($item_id);
if(empty($item)) {
return response()->json([
'success' => false,
'message' => 'Item not found!',
], 404);
} else {
$item->name = $request->get('language_name');
$item->save();
return response()->json([
'success' => true,
'message' => 'Item successfully updated.',
], 200);
}
}
ROUTES
// ...
// book_languages
Route::group(['prefix' => 'book-languages', 'as' => 'admin.book_languages.',], function () {
Route::get('all', 'BookLanguageController#index')->name('index');
Route::get('ajax', 'BookLanguageController#ajax')->name('ajax');
Route::post('update', 'BookLanguageController#update')->name('edit');
Route::post('delete', 'BookLanguageController#delete')->name('delete');
});
// ...
I think this can help you and others to build wanted functionality. Here this could be also with more hint-comments, but as it not small, I can answer later via post comments.
i am building a Laravel ERP-like web application and am implementing a CRUD function modal like you. I have made mine a server-side processing application with resource APIs in Laravel. Well, please be reminded that i have cut the #extends(layout.app) & #section('stylesheet') parts to go right into the answer. You should extend them in your own application to make everything work.
View.blade script
<script>
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var table = $('#customertable').DataTable({
processing: true,
serverSide: true,
dom: 'B<"top"frli>tp',
ajax: {
url: "{{ route('customer.index') }}", //Accessing server for data
columns: [
{data: 'id'}, //data refers to DB column name
{data: 'name'},
{data: 'chiname'},
{data: 'type'},
{data: 'action'}, //this is an addColumn item from Controller
]
});
$('#createNewcustomer').click(function () {
$('#saveBtn').val("create customer");
$('#customerid').val('');
$('#customerForm').trigger("reset");
$('#modelHeading').html("Create New Customer");
$('#customermodal').modal('show');
});
//Control the modal behavior when clicking the edit button.
$('body').on('click', '.editcustomer', function () {
var customerid = $(this).data('id');
$.get("{{ route('customer.index') }}" +'/' + customerid +'/edit', function (data) {
$('#modelHeading').html("Edit Customer");
$('#saveBtn').val("edit-user");
$('#customermodal').modal('show');
$('#customerid').val(data.id);
$('#name').val(data.name);
$('#chiname').val(data.chiname);
$('#type').val(data.type);
})
});
//Create a brand-new record
$('#createNewcustomer').click(function () {
$('#saveBtn').val("create customer");
$('#customerid').val('');
$('#customerForm').trigger("reset");
$('#modelHeading').html("Create New Customer");
$('#customermodal').modal('show');
});
//Update
$('body').on('click', '.editcustomer', function () {
var customerid = $(this).data('id');
$.get("{{ route('customer.index') }}" +'/' + customerid +'/edit', function (data) {
$('#modelHeading').html("Edit Customer");
$('#saveBtn').val("edit-user");
$('#customermodal').modal('show');
$('#customerid').val(data.id);
$('#name').val(data.name);
$('#chiname').val(data.chiname);
$('#type').val(data.type);
})
});
//Save
$('#saveBtn').click(function (e) {
e.preventDefault();
$(this).html('Sending..');
$.ajax({
data: $('#customerForm').serialize(),
url: "{{ route('customer.store') }}",
type: "POST",
dataType: 'json',
success: function (data) {
$('#customerForm').trigger("reset");
$('#customermodal').modal('hide');
table.draw();
},
error: function (data) {
console.log('Error:', data);
$('#saveBtn').html('Error');}
});
});
//Delete
$('body').on('click', '.deletecustomer', function () {
var id = $(this).data("id");
confirm("Are You sure?");
$.ajax({
type: "DELETE",
url: "{{ route('customer.store') }}"+'/'+id,
success: function (data) {
table.draw();
},
error: function (data) {
console.log('Error:', data);
}
});
});
</script>
View.blade html-table & modal part
#section('content')
<div class="container">
<div class="card-header border-left"><h3><strong> Customer overview</strong></h3></div>
<br>
<div class="row">
<div class="col-md text-right">
<button type="button" class="btn btn-success" data-toggle="modal" href="javascript:void(0)" id="createNewcustomer">Create Record</button>
</div>
</div>
{{-- Modal --}}
<div id="customermodal" class="modal fade" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="modelHeading"></h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times</span></button></div>
<div class="modal-body">
<form id="customerForm" name="customerForm" class="form-horizontal">
<input type="hidden" name="customerid" id="customerid">
<div class="form-group">
<label for="name" class="col-sm-6 control-label">Customer Name</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="name" name="name" placeholder="Name" value="" maxlength="50" required="">
</div>
</div>
<div class="form-group">
<label class="col-sm-6 control-label">Customer Name</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="chiname" name="chiname" placeholder="Customer Name" value="" maxlength="50" required="">
</div>
</div>
<div class="form-group">
<label class="col-sm-6 control-label">Contract type</label>
<div class="col-sm-12">
<select name="type" id="type" class="form-control">
<option value="" disabled>Type</option>
<option value="Government">Government Contract</option>
<option value="Private">Private Contract</option>
</select>
</div></div>
<br>
<div class="col-sm text-right">
<button type="submit" class="btn btn-outline-secondary" id="saveBtn" value="create">Save changes</button>
</div>
</form>
</div>
</div>
</div>
</div>
{{-- Table --}}
<br>
<div class="row">
<br/>
<br/>
<div class="form-group col-md-12 align-content-center">
<table class="table-fluid center-block" id="customertable">
<thead>
<tr>
<th>id</th>
<th>ChiName</th>
<th>Name</th>
<th>Type</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
#endsection
CustomerController
public function index(Request $request)
{
$customers = Customer::all();
}
return Datatables::of($customers)
->addColumn('action', function($customer){
$btn = 'Edit';
$btn = $btn.' Delete';
return $btn;})
->rawColumns(['action'])
->make(true);
}
return view('customer.Customer'); //my view blade is named Customer under customer dir. put your blade destination here.
}
public function store(Request $request)
{
Customer::updateOrCreate(['id' => $request->customerid],
['name' => $request->name, 'chiname' => $request->chiname,'type' =>$request->type]);
return response()->json(['success'=>'Product saved successfully.']);
}
public function edit($id)
{
$customer = Customer::findorfail($id);
return response()->json($customer);
}
public function destroy($id)
{
Customer::findorfail($id)->delete();
return response()->json(['success'=>'Product deleted successfully.']);
}
Model (pick either A.) $guarded = [] OR B.) $fillable = ['fields','fields'] as you like)
class Customer extends Model
{
protected $fillable = ['name','chiname','type'];
}
web.api (route setting)
Route::resource('customer', 'CustomerController')->middleware('auth');
Migration / DB schema structure
class CreateCustomersTable extends Migration
{
public function up()
{
Schema::create('customers', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('chiname');
$table->string('type');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('customers');
}
I have not included any protection in it like gate, auth or so. But basically this is the skeleton of doing CRUD with dataTable in Laravel framework with both JS, Ajax, Jquery, PHP all in one. Kindly be reminded that the queries for such CRUD actions are directly linked to the Database server. If you want to show data processed by the DataTable, use your own jquery function to fetch and show them on the modal. My answer is not the best but i hope it helps you >:)
(I could not post a picture to show you here as i dont have enough reputation lol. gg)

Why can't the edit-modal fetch the data(of the selected row) from my database?

So this is my brand.php file
And it portrays the edit part of the brand
so in this part we can probably see how the thing will look like
<!-- edit brand -->
<div class="modal fade" id="editBrandModel" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<form class="form-horizontal" id="editBrandForm" action="php_action/editBrand.php" method="POST">
<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"><i class="fa fa-edit"></i> Edit Brand</h4>
</div>
<div class="modal-body">
<div id="edit-brand-messages"></div>
<div class="modal-loading div-hide" style="width:50px; margin:auto;padding-top:50px; padding-bottom:50px;">
<i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i>
<span class="sr-only">Loading...</span>
</div>
<div class="edit-brand-result">
<div class="form-group">
<label for="editBrandName" class="col-sm-3 control-label">Brand Name: </label>
<label class="col-sm-1 control-label">: </label>
<div class="col-sm-8">
<input type="text" class="form-control" id="editBrandName" placeholder="Brand Name" name="editBrandName" autocomplete="off">
</div>
</div> <!-- /form-group-->
<div class="form-group">
<label for="editBrandStatus" class="col-sm-3 control-label">Status: </label>
<label class="col-sm-1 control-label">: </label>
<div class="col-sm-8">
<select class="form-control" id="editBrandStatus" name="editBrandStatus">
<option value="">~~SELECT~~</option>
<option value="1">Available</option>
<option value="2">Not Available</option>
</select>
</div>
</div> <!-- /form-group-->
</div>
<!-- /edit brand result -->
</div> <!-- /modal-body -->
<div class="modal-footer editBrandFooter">
<button type="button" class="btn btn-default" data-dismiss="modal"> <i class="glyphicon glyphicon-remove-sign"></i> Close</button>
<button type="submit" class="btn btn-success" id="editBrandBtn" data-loading-text="Loading..." autocomplete="off"> <i class="glyphicon glyphicon-ok-sign"></i> Save Changes</button>
</div>
<!-- /modal-footer -->
</form>
<!-- /.form -->
</div>
<!-- /modal-content -->
</div>
<!-- /modal-dailog -->
</div>
<!-- / add modal -->
<!-- /edit brand -->
> --this one is the end part
And this is the fetching part, wherein once you click the button from the row(example row 1), a modal(Edit Modal will likely appear), but the thing is, once the modal appear, the data that is supposed to be fetched from the row is not on that modal ;-;
<?php
require_once '../../includes/connection.php';
$brandId = $_POST['brandId'];
$sql = "SELECT brand_id, brand_name, brand_active, brand_status FROM brands WHERE brand_id = $brandId";
$result = $connect->query($sql);
if($result->num_rows > 0) {
$row = $result->fetch_array();
} // if num_rows
$connect->close();
echo json_encode($row);
?>
Now the JScript part
This part is the filler part(like getting the data and now portraying the data and filling the input boxes etc..)
function editBrands(brandId = null) {
if(brandId) {
// remove hidden brand id text
$('#brandId').remove();
// remove the error
$('.text-danger').remove();
// remove the form-error
$('.form-group').removeClass('has-error').removeClass('has-success');
// modal loading
$('.modal-loading').removeClass('div-hide');
// modal result
$('.edit-brand-result').addClass('div-hide');
// modal footer
$('.editBrandFooter').addClass('div-hide');
$.ajax({
url: 'fetchSelectedBrand.php',
type: 'post',
data: {brandId : brandId},
dataType: 'json',
success:function(response) {
// modal loading
$('.modal-loading').addClass('div-hide');
// modal result
$('.edit-brand-result').removeClass('div-hide');
// modal footer
$('.editBrandFooter').removeClass('div-hide');
// setting the brand name value
$('#editBrandName').val(response.brand_name);
// setting the brand status value
$('#editBrandStatus').val(response.brand_active);
// brand id
$(".editBrandFooter").after('<input type="hidden" name="brandId" id="brandId" value="'+response.brand_id+'" />');
// update brand form
$('#editBrandForm').unbind('submit').bind('submit', function() {
// remove the error text
$(".text-danger").remove();
// remove the form error
$('.form-group').removeClass('has-error').removeClass('has-success');
var brandName = $('#editBrandName').val();
var brandStatus = $('#editBrandStatus').val();
if(brandName == "") {
$("#editBrandName").after('<p class="text-danger">Brand Name field is required</p>');
$('#editBrandName').closest('.form-group').addClass('has-error');
} else {
// remov error text field
$("#editBrandName").find('.text-danger').remove();
// success out for form
$("#editBrandName").closest('.form-group').addClass('has-success');
}
if(brandStatus == "") {
$("#editBrandStatus").after('<p class="text-danger">Brand Name field is required</p>');
$('#editBrandStatus').closest('.form-group').addClass('has-error');
} else {
// remove error text field
$("#editBrandStatus").find('.text-danger').remove();
// success out for form
$("#editBrandStatus").closest('.form-group').addClass('has-success');
}
if(brandName && brandStatus) {
var form = $(this);
// submit btn
$('#editBrandBtn').button('loading');
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
dataType: 'json',
success:function(response) {
if(response.success == true) {
console.log(response);
// submit btn
$('#editBrandBtn').button('reset');
// reload the manage member table
manageBrandTable.ajax.reload(null, false);
// remove the error text
$(".text-danger").remove();
// remove the form error
$('.form-group').removeClass('has-error').removeClass('has-success');
$('#edit-brand-messages').html('<div class="alert alert-success">'+
'<button type="button" class="close" data-dismiss="alert">×</button>'+
'<strong><i class="glyphicon glyphicon-ok-sign"></i></strong> '+ response.messages +
'</div>');
$(".alert-success").delay(500).show(10, function() {
$(this).delay(3000).hide(10, function() {
$(this).remove();
});
}); // /.alert
} // /if
}// /success
}); // /ajax
} // /if
return false;
}); // /update brand form
} // /success
}); // ajax function
} else {
alert('error!! Refresh the page again');
}
} // /edit brands function
Can you check the Network tab to see the result from server? You can debug your app by seeing that result.
By the way, there're two things that you may need to edit:
1/ If brandId is interger, you need to get it from $_GET by intval($_POST['brandId']) to prevent SQL Injection.
2/
if($result->num_rows > 0) {
$row = $result->fetch_array();
}
else {
$row = array();
}
your code need to return empty array if sql result is empty to avoid Undefined variable error.

keep the modal open after form submit in codeigniter and trying a bit of ajax

so this is my controller:
User_Authentication_Controller:
public function login_user(){
$username = $this->input->post('txt_login_username');
$password = md5($this->input->post('txt_login_password'));
$result=$this->LogIn_Model->login($username,$password);
redirect('Pages_Controller/homepage');
}
LogIn_Model:
public function LogIn($username,$password){
$data = array(
'username' => $username,
'password' => $password
);
$query = $this->db->get_where('user_account',$data);
return $query->result_array();
}
LOGIN MODAL:
<section id="login_modal" class="modal fade" >
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header"></div>
<div class="modal-body" id="forms">
<div class="loginmodal-container">
<h1>Login to Your Account</h1><br>
<form class="form-horizontal" id="form_login" action="" method="POST">
<div class='error_msg'></div>
<input autofocus="autofocus" type="text" id="txt_login_username" name="txt_login_username" class="form-control" />
<input type="password" id="txt_login_password" name="txt_login_password" class="form-control" />
<button class="btn btn-primary" type="submit" name="btnLogin">Login</button>
Forgot Password?
</div>
</form>
</div>
<div class="modal-footer">
<center><button type = "submit" id="login_user" class="btn btn-danger" data-dismiss="modal" >CLOSE</button></center>
</div>
</div>
</div>
</section>
VIEW:
Login
AJAX:
$(function(){
$('#login_user').submit(function(event){
var user = $('#txt_login_username').val();
var pass = $('#txt_login_password').val();
$.ajax({
type: 'POST',
url: 'User_Authentication_Controller/login_user',
data: {
'user': user,
'pass': pass
},
dataType: 'html',
success: function(results){
if(user != user){
$('.error_msg').html('error msg');
return false;
}
}
});
});
});
ALL I WANT IS IF THERE IS AN ERROR! THE will work and the modal will not close! how will I do that with CI? Is there any possible way that just put the LogIn_Model->login(); in AJAX? please help! I need this thing badly! And in addition I want that what the user inputs and if he got it wrong when he submitted the username will still be at the textbox! how will I do that also? THank you so much for help!

AngularJS - object not passed to modal dialog

I have a problem with an AngularJS app I'm making. It shows a list of contacts, and for each contact there is a button whereupon clicking the button a modal pops up with a form. This form should show the existing contact information, and if you want to change something you type the new information and press submit.
The problem, however, is that the existing information is not shown in the form, hence editing it doesn't work. I imagine that the issue is that the modal does not inherit the scope from the parent page, but I don't know what to do in order to fix that. I have tried playing around with the attributes on the input fields (for example prepending ng-model by $parent. and defining an ng-init value), but to no avail, so I hope some of the experts here will be able to point me on the right track.
Thank you in advance.
Now let me show you my code, so you can see the context I'm talking about. Here is the html that displays the list of contacts:
<div class="panel panel-default" ng-controller="contactsController">
<div class="panel-body">
<div id="gridContainer" ng-class="{'': state == 'list', 'none': state != 'list'}">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th scope="col"><spring:message code="contacts.name"/></th>
<th scope="col"><spring:message code="contacts.email"/></th>
<th scope="col"><spring:message code="contacts.phone"/></th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="contact in page.source">
<td class="tdContactsCentered">{{contact.name}}</td>
<td class="tdContactsCentered">{{contact.email}}</td>
<td class="tdContactsCentered">{{contact.phoneNumber}}</td>
<td class="width15">
<div class="text-center">
<input type="hidden" value="{{contact.id}}"/>
<a ng-href="#updateContactsModal"
ng-click="selectedContact(contact);"
role="button"
title="<spring:message code="update"/> <spring:message code="contact"/>"
class="btn btn-sm btn-warning" data-toggle="modal">
<i class="icon-pencil"></i>
</a>
<a ng-href="#deleteContactsModal"
ng-click="selectedContact(contact);"
role="button"
title="<spring:message code="delete"/> <spring:message code="contact"/>"
class="btn btn-sm btn-danger" data-toggle="modal">
<em class="fa fa-trash"></em>
</a>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
And the html that defines the modal and the form:
<div id="updateContactsModal"
class="modal fade centering"
role="dialog"
aria-labelledby="updateContactsModalLabel"
aria-hidden="true" style="display: none;">
<div class="modal-dialog" role="document">
<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>
<h3 id="updateContactsModalLabel" class="modal-title">
<spring:message code="update"/> <spring:message code="contact"/>
</h3>
</div>
<div class="modal-body" data-ng-controller="contactsController">
<form name="updateContactForm" novalidate>
<input type="hidden"
required
data-ng-model="contact.id"
name="id"
value="{{contact.id}}"/>
<div>
<div class="form-group">
<label>* <spring:message code="contacts.name"/>:</label>
<input type="text"
autofocus
required
class="form-control"
data-ng-model="contact.name"
name="name"
placeholder="<spring:message code='contact'/> <spring:message code='contacts.name'/> "/>
<div>
<span class="alert alert-error"
ng-show="displayValidationError && updateContactForm.name.$error.required">
<spring:message code="required"/>
</span>
</div>
</div>
<div class="form-group">
<label>* <spring:message code="contacts.email"/>:</label>
<div class="input-append">
<input type="text"
required
class="form-control"
ng-model="contact.email"
name="email"
placeholder="<spring:message code='sample.email'/> "/>
</div>
<div>
<span class="alert alert-error"
ng-show="displayValidationError && updateContactForm.email.$error.required">
<spring:message code="required"/>
</span>
</div>
</div>
<div class="form-group">
<label>* <spring:message code="contacts.phone"/>:</label>
<div class="input-append">
<input type="text"
required
class="form-control"
ng-model="contact.phoneNumber"
name="phoneNumber"
placeholder="<spring:message code='sample.phone'/> "/>
</div>
<div>
<span class="alert alert-error"
ng-show="displayValidationError && updateContactForm.phoneNumber.$error.required">
<spring:message code="required"/>
</span>
</div>
</div>
</div>
</form>
<div class="modal-footer">
<input type="submit"
class="btn btn-primary"
ng-click="updateContact(updateContactForm);"
value='<spring:message code="update"/>'/>
<button class="btn btn-default"
data-dismiss="modal"
ng-click="exit('#updateContactsModal');"
aria-hidden="true">
<spring:message code="cancel"/></button>
</div>
</div>
<span class="alert alert-error dialogErrorMessage"
ng-show="errorOnSubmit">
<spring:message code="request.error"/>
</span>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
And finally the relevant parts of the controller:
App.controller('contactsController', ["$scope", "$http", function($scope,$http) {
$scope.pageToGet = 0;
$scope.state = 'busy';
$scope.lastAction = '';
$scope.url = "/uaiContacts/protected/contacts/";
$scope.errorOnSubmit = true;
$scope.errorIllegalAccess = false;
$scope.displayMessageToUser = false;
$scope.displayValidationError = false;
$scope.displaySearchMessage = false;
$scope.displaySearchButton = false;
$scope.displayCreateContactButton = false;
$scope.contact = {};
$scope.searchFor = "";
$scope.getContactList = function () {
var url = $scope.url;
$scope.lastAction = 'list';
$scope.startDialogAjaxRequest();
var config = {params: {page: $scope.pageToGet}};
$http.get(url, config)
.success(function (data) {
$scope.finishAjaxCallOnSuccess(data, null, false);
})
.error(function () {
$scope.state = 'error';
$scope.displayCreateContactButton = false;
});
};
$scope.populateTable = function (data) {
if (data.pagesCount > 0) {
$scope.state = 'list';
$scope.page = {source: data.contacts, currentPage: $scope.pageToGet, pagesCount: data.pagesCount, totalContacts : data.totalContacts};
if($scope.page.pagesCount <= $scope.page.currentPage){
$scope.pageToGet = $scope.page.pagesCount - 1;
$scope.page.currentPage = $scope.page.pagesCount - 1;
}
$scope.displayCreateContactButton = true;
$scope.displaySearchButton = true;
} else {
$scope.state = 'noresult';
$scope.displayCreateContactButton = true;
if(!$scope.searchFor){
$scope.displaySearchButton = false;
}
}
if (data.actionMessage || data.searchMessage) {
$scope.displayMessageToUser = $scope.lastAction != 'search';
$scope.page.actionMessage = data.actionMessage;
$scope.page.searchMessage = data.searchMessage;
} else {
$scope.displayMessageToUser = false;
}
};
$scope.exit = function (modalId) {
$(modalId).modal('hide');
$scope.contact = {};
$scope.errorOnSubmit = false;
$scope.errorIllegalAccess = false;
$scope.displayValidationError = false;
};
$scope.finishAjaxCallOnSuccess = function (data, modalId, isPagination) {
$scope.populateTable(data);
$("#loadingModal").modal('hide');
if(!isPagination){
if(modalId){
$scope.exit(modalId);
}
}
$scope.lastAction = '';
};
$scope.startDialogAjaxRequest = function () {
$scope.displayValidationError = false;
$("#loadingModal").modal('show');
$scope.previousState = $scope.state;
$scope.state = 'busy';
};
$scope.handleErrorInDialogs = function (status) {
$("#loadingModal").modal('hide');
$scope.state = $scope.previousState;
// illegal access
if(status == 403){
$scope.errorIllegalAccess = true;
return;
}
$scope.errorOnSubmit = true;
$scope.lastAction = '';
};
$scope.addSearchParametersIfNeeded = function(config, isPagination) {
if(!config.params){
config.params = {};
}
config.params.page = $scope.pageToGet;
if($scope.searchFor){
config.params.searchFor = $scope.searchFor;
}
};
$scope.selectedContact = function (contact) {
$scope.contact = angular.copy(contact);
debugger;
};
$scope.updateContact = function (updateContactForm) {
if (!updateContactForm.$valid) {
debugger;
$scope.displayValidationError = true;
return;
}
$scope.lastAction = 'update';
var url = $scope.url + $scope.contact.id;
$scope.startDialogAjaxRequest();
var config = {};
$scope.addSearchParametersIfNeeded(config, false);
$http.put(url, $scope.contact, config)
.success(function (data) {
$scope.finishAjaxCallOnSuccess(data, "#updateContactsModal", false);
})
.error(function(data, status, headers, config) {
$scope.handleErrorInDialogs(status);
});
};
$scope.getContactList();
}]);
The modal doesn't share the same scope as the contacts table because each time Angular finds another ng-controller directive, it creates a new scope.
You're declaring ng-scope in both the contacts table and the modal, which causes angular to create different scopes.
See this answer for more details:
https://stackoverflow.com/a/14462341/4938335
There are a few ways to solve this...
1) Put the modal HTML inside the parent element where you're already declaring ng-controller the first time - that way it will be part of the same scope
2) Use UI Bootstrap's modal directive to generate the modal with its own controller and pass in $scope.contact from your contactsController. See example here https://angular-ui.github.io/bootstrap/#/modal
3) Create a service that stores $scope.contact and inject that into a separate controller that you create for the modal. Here's someone else's fiddle that shows this:
http://jsfiddle.net/whnSs/

Categories

Resources