I am new to angularJS as well as MVC. Just tried a simple CRUD operation .
The GetallEmployee() and the edit operation call are working fine. However the submit is not working. I am sure there is a lot of blunder in the code .Apologies for that .
Here is my Controller and service and view that I added....
app.controller("myController", ['$scope', '$http', 'angularService', function ($scope, $http, angularService) {
$scope.employees = [];
var fetched = angularService.GetAllEmployee();
fetched.then(function (emps) {
$scope.employees = emps.data;
});
$scope.editEmployee = function (data) {
var Emp = $http({
method: "get",
url: "Home/GetEmployeebyId",
params: {
Id: JSON.stringify(data.ID)
}
}).success(function (Emp) {
$scope.employeeName = Emp.Name;
$scope.employeeId = Emp.ID;
$scope.employeeEmail = Emp.Email;
$scope.employeeAge = Emp.Age;
$scope.Action = "Update";
$scope.IsIndian = Boolean(Emp.IsIndian);
$scope.employeeGender = Emp.Gender;
});
};
$scope.AddUpdateEmployee = function () {
var Employee = {
Id: $scope.employeeId,
Name: $scope.employeeName,
Email: $scope.employeeEmail,
Age: $scope.employeeAge,
Gender: $scope.employeeGender,
IsIndian: $scope.IsIndian,
};
var getAction = $scope.Action;
if (getAction == 'Update') {
Employee.Id = $scope.employeeId;
$http({ method: 'post', url: 'Home/UpdateEmployee', data: JSON.stringify(Employee), datatype: 'json' }).success
(function (output) {
var fetched = angularService.GetAllEmployee();
fetched.then(function (emps)
{
$scope.employees = emps.data;
}
)
ClearFields();
});
}
else {
$http({ method: 'post', url: 'Home/AddEmployee', data: JSON.stringify(Employee), datatype: 'json' }).success
(function () {
var fetched = angularService.GetAllEmployee();
fetched.then(function (emps) {
$scope.employees = emps.data;
alert(output);
ClearFields();
});
}
);
}
$scope.Action = "";
}
////$scope.deleteEmployee = function (employee) {
//// angularService.deleteEmployee(employee.ID).then(function (msg) {
//// GetAllEmployee();
//// alert(msg.data);/////earlier it was a string message in place if msg.data
//// }, function () {
//// alert('Error in Deleting Record');
//// });
////}
function ClearFields() {
$scope.employeeId = "";
$scope.employeeName = "";
$scope.employeeEmail = "";
$scope.employeeAge = "";
$scope.IsIndian = false;
$scope.Gender = 'Male';
}
}]);
app.service("angularService", function ($http) {
//get All Eployee
var temp = this;
temp.employee = [];
this.GetAllEmployee = function () {
return $http.get("Home/GetAll").success(function (emps) {
emps.forEach(function (eachemp) {
eachemp.IsIndian = Boolean(eachemp.IsIndian);
temp.employee.push(eachemp);
})
});
}
});
#{
ViewBag.Title = "Home Page";
}
<div ng-controller="myController as myController" ng-app="MyApp">
<br />
<div>
<table class="table ">
<tr>
<td colspan="6" align="center">
<label style="font-family:Arial ;font-weight:bold">Employee Details</label>
</td>
</tr>
<tr>
<td style="font-weight:bold">Name</td>
<td style="font-weight:bold">Id</td>
<td style="font-weight:bold">Email</td>
<td style="font-weight:bold">Age</td>
<td style="font-weight:bold"></td>
</tr>
<tr ng-repeat="emp in employees">
<td>{{emp.Name}}</td>
<td>{{emp.ID}}</td>
<td>{{emp.Email}}</td>
<td>{{emp.Age}}</td>
<td>
<button ng-click="editEmployee(emp)" type="submit" class="btn btn-primary">Edit</button>
<button ng-click="deleteEmployee(emp)" type="submit" class="btn btn-primary">Delete</button>
</td>
<td>
<input type="checkbox" ng-model="emp.IsIndian" disabled="disabled" name="IndianChk" /> Indian
<input type="radio" disabled="disabled" ng-model="emp.Gender" value="Male"> Male
<input type="radio" disabled="disabled" ng-model="emp.Gender" value="Female" />Female
</td>
</tr>
</table>
</div>
<form name="form" ng-submit="myController.addupdateemployee()">
<table class="table table-responsive">
<tr>
<td>
<label>Employee ID </label>
</td>
<td>
<input type="text" disabled="disabled" ng-model="employeeId" class="form-control" />
</td>
</tr>
<tr>
<td>
<label>Employee Name </label>
</td>
<td>
<div class="form-group" ng-class="{'has-error': form.empname.$invalid && form.empname.$dirty }">
<input type="text" ng-model="employeeName" class="form-control" required name="empname" />
</div>
</td>
</tr>
<tr>
<td>
<label>Employee Email </label>
</td>
<td>
<div class="form-group" ng-class="{'has-error': form.mail.$invalid && form.mail.$dirty }">
<input type="text" ng-model="employeeEmail" class="form-control" required name="mail" />
</div>
</td>
</tr>
<tr>
<td>
<label>Gender</label>
</td>
<td>
<div>
<select class="form-control" ng-model="employeeGender" required>
<option>Male</option>
<option>Female</option>
</select>
</div>
</td>
</tr>
<tr>
<td>
<label>Employee Age </label>
</td>
<td>
<div class="form-group">
<input type="number" ng-model="employeeAge" required class="form-control" name="age">
</div>
</td>
</tr>
<tr>
<td>
<label>Is Indian </label> <input type="checkbox" ng-model="IsIndian" ng-required="true" />
</td>
</tr>
<tr>
<td colspan="2">
<button type="submit" class="btn btn-primary" name="submit">submit</button>
</td>
</tr>
</table>
</form>
</div>
Change your form tag from:
<form name="form" ng-submit="myController.addupdateemployee()">
to
<form ng-submit="AddUpdateEmployee()" ng-controller="myController">
Related
I am trying to save data using Angularjs and web API under some conditions or "if statement" or selection from the user . Inaddition to input texts, The conditions are : if the user select first item in first combo box and first item in second combo box the insertion value should be 1. If the user select the second item in first combo box and first item in second combo box the insertion value should be 2. If the user select the first item in first combo box and second item in second combo box the insertion value should be 3. and so on
I am using the post method in angular service. what is the correct code because when debug i got errors, thanks in advance.
HTML
<body ng-app="ContractT" ng-controller="crudController">
<br /><br />
<input type="checkbox" ng-model="Hide" />Hide <input type="button" value="Clear" ng-click="resetform()" />
<input type="submit" value="Save" ng-click="save()"/> <input type="button" value="Delete" ng-click="delete(selectedMember.sys_key)" />
<fieldset>
<legend>Contract Type</legend>
<table>
<tr>
<td>Code</td>
<td><input type="text" size="10" pattern="^[a-zA-Z0-9]+$" title="Alphnumeric" required autofocus ng-model="selectedMember.Code.Staff_Type_Code">
<input type="text" size="10" hidden ng-model="selectedMember.sys_key" /> </td>
</tr>
<tr>
<td>Latin Description</td>
<td><input type="text" required size="35" ng-model="selectedMember.Latin.L_Desc"></td>
</tr>
<tr>
<td>Local Description</td>
<td><input type="text" required size="35" ng-model="selectedMember.Local.A_Desc"></td>
</tr>
<tr>
<td>No. Of Houres Per Day</td>
<td><input type="text" pattern="^[0-9]+$" title="Please enter numbers only" size="10" maxlength="2" ng-model="selectedMember.Hours_Day"></td>
</tr>
<tr>
<td>No. Of Days Per Week(s)</td>
<td><input type="text" pattern="^[0-9]+$" title="Please enter numbers only" size="10" maxlength="2" ng-model="selectedMember.Days_Week"></td>
</tr>
<tr>
<td>End Of Contract By</td>
<td>
<select>
<option ng-model="Age">Age</option>
<option ng-model="NYears">Number Of Years in Service</option>
</select>
</td>
</tr>
<tr>
<td>Number</td>
<td>
<input type="text" pattern="^[0-9]+$" title="Please enter numbers only" size="10" maxlength="2" ng-model="selectedMember.Num_EndWork">
<select>
<option ng-model="Months">Months</option>
<option ng-model="Years">Years</option>
</select>
</td>
</tr>
</table>
</fieldset>
<br />
<table border="1" ng-hide="Hide">
<thead>
<tr>
<!--<th>syskey</th>-->
<th>Code</th>
<th>Latin Description</th>
<th>Local Description</th>
<th>Hours_Day</th>
<th>Days_Week</th>
<th>Num_EndWork</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="c in Contracts | filter:selectedMember.Code | filter:selectedMember.Latin | filter:selectedMember.Local ">
<td style="display:none;">{{c.sys_key}}</td>
<td>{{c.Staff_Type_Code}}</td>
<td>{{c.L_Desc}}</td>
<td>{{c.A_Desc}}</td>
<td>{{c.Hours_Day}}</td>
<td>{{c.Days_Week}}</td>
<td>{{c.Num_EndWork}}</td>
</tr>
</tbody>
</table>
</form>
Controller
contractT.controller('crudController', function ($scope, crudService)
{
loadrecords();
function loadrecords()
{
crudService.getContracts().then(function (response) {
$scope.Contracts = (response.data);
$scope.selectedMember = {};
console.log($scope.Contracts);
});
}
$scope.save = function () {
debugger;
var Contract = { Code: $scope.Staff_Type_Code, Latin: $scope.L_Desc, Local: $scope.A_Desc, Nend: $scope.Num_EndWork, Tend: $scope.Type_EndWork, hd: $scope.Hours_Day, dw: $scope.Days_Week }
if ($scope.Type_EndWork == "Age" && $scope.Days_Month == "Months")
$scope.Type_EndWork = 1
else if ($scope.Type_EndWork == "Age" && $scope.Days_Month == "Years")
$scope.Type_EndWork = 2
else if ($scope.Type_EndWork == "NYears" && $scope.Days_Month == "Months")
$scope.Type_EndWork = 3
else ($scope.Type_EndWork == "NYears" && $scope.Days_Month == "Years")
$scope.Type_EndWork = 4
if ($scope.selectedMember.sys_key == {}) {
var promisesave = crudService.post(Contract);
promisesave.then(function (pl) {
$scope.selectedMember = {};
loadrecords();
}, function (err) {
console.log("Err" + err);
});
}
}
$scope.resetform = function () {
$scope.selectedMember = {};
//$scope.selectedMember = {};
//$scope.Local = {};
//$scope.Nhd = null;
//$scope.Ndw = null;
//$scope.Num = null;
}
$scope.selectedMember = { Code: "",sys_key:"", Latin:"" , Local:"", Hours_Day :"", Days_Week:"", Num_EndWork:"" }
$scope.showInEdit = function (member)
{
$scope.selectedMember = member;
$scope.selectedMember.Code = member;
$scope.selectedMember.Latin = member;
$scope.selectedMember.Local = member;
//$scope.selectedMember.Hours_Day = member;
//$scope.selectedMember.Days_Week = member;
//$scope.selectedMember.Num_EndWork = member;
}
the service is
this.post = function(Contract) {
var request = $http({
method: "post",
url: "/ContractTypesAPI/api/ContractTypes/addContract",
data: JSON.stringify(Contract),
dataType: "json"
});
};
I have a form which have textbox,selectbox and checkbox. I want to display the values in the form in a grid table in the same page when the save button is clicked. I was able to display the textbox and selectbox value .But I dont know how to display the selected checkbox value.
HTML code:
<div ng-controller="ProductCtrl">
<form class=rform align="center">
Product Name: <input type="text" name="name" ng-model="newProduct.name" ><br>
Product Category: <select name="catg" ng-model="newProduct.catg" ng-options="x for x in catg" ></select><br>
Tags :<input type="checkbox" name="Electronics" ng-model="newProduct.Electronics" value="Electronics" >Electronics
<input type="checkbox" name="Appliances" ng-model="newProduct.Appliances" value="Appliances">Appliances
<input type="checkbox" name="Others" ng-model="newProduct.Others" value="Books">Others
<input type="hidden" ng-model="newProduct.id" />
<div class="btn"> <button type="submit" ng-click="saveRecord()">Save</button></div>
</form>
<table border="2px" align="center" >
<tr>
<th>Product name</th>
<th>Category</th>
<th>Tag</th>
<th>id</th>
<th>Action</th>
</tr>
<tr ng-repeat="product in products">
<td>{{ product.name }}</td>
<td>{{ product.catg }}</td>
<td>{{ product.tag }}</td>
<td>{{product.id}}</td>
<td> edit |
delete</td>
</tr>
</table>
</div>
controller :
app.controller('ProductCtrl',function($scope,$http){
$scope.catg = ["mobile","TV","Air Conditioner","Kitchen appliances","Footwear","SportsWear","clothes","watches"];
var empid =0;
var id = 0;
$scope.products= [
{ id:'' , 'name': '', 'catg': '', 'tag': '' }
];
$scope.saveRecord = function () {
if ($scope.newProduct.id == null) {
$scope.newProduct.id = empid++;
$scope.products.push($scope.newProduct);
} else {
for (i in $scope.products) {
if ($scope.products[i].id == $scope.newProduct.id) {
$scope.products[i] = $scope.newProduct;
}
}
}
$scope.newProduct = {};
}
$scope.delete = function (id) {
for (i in $scope.products) {
if ($scope.products[i].id == id) {
$scope.products.splice(i, 1);
$scope.newProduct = {};
}
}
}
$scope.edit = function (id) {
for (i in $scope.products) {
if ($scope.products[i].id == id) {
$scope.newProduct = angular.copy($scope.products[i]);
}
}
}
}
);
you can change checkbox's checked/unchecked value from true/false to custom string by ng-true-value(checked) and ng-false-value(unchecked).
and if you want the same feature for radiobutton(guessed from your comment), you can bind custom string to each radio button by ng-value.
refer the below example.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app ng-init="value='YES';value2='option1';">
<label>
<input type="checkbox" ng-model="value" ng-true-value="'YES'" ng-false-value="'NO'">checkbox</label><br> {{value}}
<br>
<label><input type="radio" name="option" ng-model="value2" ng-value="'option1'">{{option1}}</label>
<label><input type="radio" name="option" ng-model="value2" ng-value="'option2'">{{option2}}</label>
<label><input type="radio" name="option" ng-model="value2" ng-value="'option3'">{{option3}}</label>
<br>
{{value2}}
</div>
ng-fileupload having injection error on angular 1.2.3 my source code attached here
<!DOCTYPE html>
<html ng-app ="dashboard">
<head>
<title></title>
<script src="angular.min.js"></script>
<script src="angular-ui-router.js"></script>
</head>
<body>
<div class="box-content">
<form ng-controller="mycontroller as up" name="up.upload_form">
<table cellspacing="10" cellpadding="10" style="margin-left: 5%; cellspacing= 7;">
<tr>
<td>
<label class="control-label" for="inputSuccess1">Course Name</label></td>
<td>
<input type="text" name="coursename" ng-model=" up.coursename" placeholder="Enter course name here" class="form-control">
</td>
</tr>
<tr>
<td>
<label class="control-label" for="inputSuccess1">Course Code</label></td>
<td><input type="text" name="coursecode" ng-model=" up.coursecode" placeholder="Enter course code here" class="form-control"></td>
</tr>
<tr>
<td>
<label class="control-label" for="inputSuccess1">Course Title</label></td>
<td><input type="text" name="coursetitle" ng-model=" up.coursetitle" placeholder="Enter course title here" class="form-control"></td>
</tr>
<tr>
<td>
<label class="control-label" for="inputSuccess1">Course Authur</label></td>
<td> <input type="text" name="courseauthor" ng-model=" up.courseauthor" placeholder="Enter author name here" class="form-control"></td>
</tr>
<tr>
<td>
<label class="control-label" for="inputSuccess1">Course Discription</label></td>
<td><textarea name="coursediscription" ng-model=" up.coursediscription" placeholder="Enter course description here"></textarea></td>
</tr>
<tr>
<td>
<label class="control-label" for="inputSuccess1">Course urlpath</label></td>
<td> <input type="text" name="courseurlpath" ng-model=" up.courseurlpath" placeholder="Enter course url path here" class="form-control"></td>
</tr>
<tr>
<td>
<label class="control-label" for="inputSuccess1">Course Start Date</label></td>
<td> <input type="date" name="coursestartingdate" ng-model=" up.coursestartingdate" placeholder="start" class="form-control"></td>
</tr>
<tr>
<td>
<label class="control-label" for="inputSuccess1">Course End Date</label></td>
<td><input type="date" name="courseendingdate" ng-model=" up.courseendingdate" placeholder="end" class="form-control"></td>
</tr>
<tr>
<td>
<label class="control-label" for="inputSuccess1">Course Attachments</label></td>
<td><input type="file" ngf-select ng-model="up.file" name="file" ngf-pattern="'image/*,application/pdf'" accept="image/*,application/pdf" ngf-max-size="20MB" class="form-control">
</td>
</tr>
<tr>
<td>
<label class="control-label" for="inputSuccess1">Course Video</label></td>
<td><input type="file" ngf-select ng-model="up.file1" name="file1" ngf-pattern="'image/*,application/pdf'" accept="image/*,application/pdf" ngf-max-size="20MB" class="form-control">
</td>
</tr>
<tr>
<td>
Image thumbnail: <img style="width:100px;" ng-show="!!up.file" ngf-thumbnail="up.file || '/thumb.jpg'" />
</td>
<td>
<i ng-show="up.upload_form.file.$error.required">*required</i><br>
<i ng-show="up.upload_form.file.$error.maxSize">File too large
{{up.file.size / 1000000|number:1}}MB: max 20M</i>
</td>
</tr>
<tr>
<td>
<button type="submit" ng-click="up.submit()" class="btn btn-success">submit</button>
<p>{{up.progress}}</p>
</form>
</td>
</tr>
<br>
</table>
</form>
</div>
</body>
<script type="text/javascript">
//var dashboard = angular.module('dashboard', ['Upload','$window''ngRoute']);
var dashboard = angular.module('dashboard', ['ui.router','Upload','$window']);
dashboard.controller('mycontroller',['Upload', '$window',function($scope,Upload, $window){
var vm = this;
vm.submit = function() {
alert("HAi")
//function to call on form submit
/* if (vm.upload_form.file.$valid && vm.file) {*/
//check if from is valid
/*vm.upload(vm.file, vm.file1, vm.coursename, vm.coursecode, vm.coursetitle, vm.courseauthor, vm.coursediscription, vm.courseurlpath, vm.coursestartingdate, vm.courseendingdate); //call upload function*/
// }
}
}]);
/* dashboard.controller('MyCtrl', ['Upload', '$window', function(Upload, $window) {
var vm = this;
vm.submit = function() {
//function to call on form submit
if (vm.upload_form.file.$valid && vm.file) {
//check if from is valid
vm.upload(vm.file, vm.file1, vm.coursename, vm.coursecode, vm.coursetitle, vm.courseauthor, vm.coursediscription, vm.courseurlpath, vm.coursestartingdate, vm.courseendingdate); //call upload function
}
}
vm.upload = function(file, file1, coursename, coursecode, coursetitle, courseauthor, coursediscription, courseurlpath, coursestartingdate, courseendingdate) {
alert("success");
Upload.upload({
url: 'http://192.168.1.16:8080/courseapi/create', //webAPI exposed to upload the file
data: {
file: file,
file1: file1,
coursename: coursename,
coursecode: coursecode,
coursetitle: coursetitle,
courseauthor: courseauthor,
coursediscription: coursediscription,
courseurlpath: courseurlpath,
coursestartingdate: coursestartingdate,
courseendingdate: courseendingdate
} //pass file as data, should be user ng-model
}).then(function(resp) {
console.log("Upload file::::" + JSON.stringify(resp));
//upload function returns a promise
if (resp.data.success === true) {
//validate success
$window.alert(resp.config.data.file.name + ' Successfully uploaded.');
} else {
$window.alert('an error occured');
}
}, function(resp) {
//catch error
console.log('Error status: ' + resp.status);
$window.alert('Error status: ' + resp.status);
}, function(evt) {
console.log(evt);
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
vm.progress = 'progress: ' + progressPercentage + '% '; // capture upload progress
});
};
}]);*/
</script>
</html>
unable to hit angularjs controller
Error stack:angular.min.js:6 Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.2.3/$injector/modulerr?p0=dashboard&p1=Error%…0A%20%20%20%20at%20e%20(http%3A%2F%2Flocalhost%2Fangular.min.js%3A28%3A374)
You don't have to inject $window and Upload to a module unless they are angualr modules,
So it should be,
var dashboard = angular.module('dashboard', ['ui.router']);
You are not injecting $scope to your function, change your controller like this,
dashboard.controller('mycontroller',['$scope','$window', 'Upload',function($scope,$window, Upload){
}]);
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...
ok, so this is my AngularJs Controller which have Directive as well.
now when i run application the main page i design for this controller is working but when i tried to re-use it as directive then i cant see anything, the new HTML page is empty.
AngularJS Controller:
var app = angular.module('dropDown', []);
app.controller('DropDownController', function ($scope, $http) {
GetCountries();
function GetCountries() {
$http({
method: 'Get',
url: '/Home/GetCountries'
}).success(function (data) {
$scope.countries = data;
}).error(function (data) {
$scope.message = 'Unexpected Error';
});
}
$scope.GetStates = function () {
var countryId = $scope.country;
if (countryId) {
$http({
method: 'POST',
url: '/Home/GetStates',
data: JSON.stringify({ countryID: countryId })
}).success(function (data) {
$scope.states = data;
}).error(function (data) {
$scope.message = 'Unexpected Error';
});
}
else {
$scope.states = null;
}
}
$scope.GetRegion = function () {
var countryId = $scope.country;
if (countryId) {
$http({
method: 'POST',
url: '/Home/GetRegion',
data: JSON.stringify({ countryID: countryId })
}).success(function (data) {
$scope.regions = data;
}).error(function (data) {
$scope.message = 'Unexpected Error';
});
}
else {
$scope.regions = null;
}
}
$scope.GetShippingStates = function () {
var countryId2 = $scope.country2;
if (countryId2) {
$http({
method: 'POST',
url: '/Home/GetStates',
data: JSON.stringify({ countryID: countryId2 })
}).success(function (data2) {
$scope.states2 = data2;
}).error(function (data2) {
$scope.message = 'Unexpected Error';
});
}
else {
$scope.states2 = null;
}
}
$scope.GetShippingRegion = function () {
var countryId2 = $scope.country2;
if (countryId2) {
$http({
method: 'POST',
url: '/Home/GetRegion',
data: JSON.stringify({ countryID: countryId2 })
}).success(function (data2) {
$scope.regions2 = data2;
}).error(function (data2) {
$scope.message = 'Unexpected Error';
});
}
else {
$scope.regions2 = null;
}
}
});
app.directive('dropdowndirective', function () {
return function() {
restrict= 'E',
transclude= true,
templateUrl= '#Url.Action("AddressControl","Home")',
//templateUrl= '/Home/AddressControl',
controller = 'DropDownController',
replace=true
}
});
MVC Controller:
using CountryAddressApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;using System.Web;
using System.Web.Mvc;
namespace CountryAddressApp.Controllers
{
public class HomeController : Controller
{
public ActionResult AddressControl()
{
return View();
}
public JsonResult GetCountries()
{
using (CountryAddressEntities context = new CountryAddressEntities())
{
var ret = context.Countries.Select(x => new { x.CountryID, x.CountryName }).ToList();
return Json(ret, JsonRequestBehavior.AllowGet);
}
}
[HttpPost]
public JsonResult GetStates(int countryId)
{
using (CountryAddressEntities context = new CountryAddressEntities())
{
var ret = context.States.Where(x => x.CountryID == countryId).Select(x => new { x.StateID, x.StateName }).ToList();
return Json(ret);
}
}
[HttpPost]
public JsonResult GetRegion(int countryId)
{
using (CountryAddressEntities context = new CountryAddressEntities())
{
var ret = context.Regions.Where(x => x.CountryID == countryId).Select(x => new { x.RegionID, x.RegionName }).ToList();
return Json(ret);
}
}
public ActionResult Index()
{
return View();
}
public ActionResult Testing()
{
return View();
}
}
}
My Main-Page
AddressControl.cshtml
#{
Layout = null;
}
<!DOCTYPE html>
<html data-ng-app="dropDown">
<head>
<meta name="viewport" content="width=device-width" />
<title>Multi-National Address</title>
<script src="~/Scripts/angular.min.js"></script>
<script src="~/Scripts/cascade.js"></script>
</head>
<body data-ng-controller="DropDownController">
<table class="container">
<tr>
<td><b>Billing Address</b></td>
<td><b>Shipping Address</b></td>
</tr>
<tr>
<td>
<div>
<div>
<form name="mainForm" data-ng-submit="sendForm()" novalidate>
<div class="error">{{message}}</div>
<div>
<table>
<tr>
<td>
<label>Select Country: </label>
</td>
<td>
<select data-ng-model="country" data-ng-options="c.CountryID as c.CountryName for c in countries" data-ng-change="GetStates()">
<option value="">-- Select Country --</option>
</select>
</td>
</tr>
</table>
</div>
<div ng-show="country==1">
<table>
<tr>
<td>
<label>Select State: </label>
</td>
<td>
<select data-ng-model="state" data-ng-disabled="!states" data-ng-options="s.StateID as s.StateName for s in states" data-ng-change="GetRegion()">
<option value="">-- Select State --</option>
</select>
</td>
</tr>
<tr>
<td>
<label>Select Region: </label>
</td>
<td>
<select data-ng-model="region" data-ng-disabled="!regions" data-ng-options="r.RegionID as r.RegionName for r in regions">
<option value="">-- Select Region --</option>
</select>
</td>
</tr>
<tr>
<td>
<label>Address:</label>
</td>
<td>
<input id="Address" name="Address" placeholder="Address" type="text" />
</td>
</tr>
<tr>
<td>
<label>Address 2:</label>
</td>
<td>
<input id="Address2" name="Address2" placeholder="Address 2" type="text" />
</td>
</tr>
<tr>
<td>
<label>City:</label>
</td>
<td>
<input id="city" name="city" placeholder="City" type="text" />
</td>
</tr>
<tr>
<td>
<label>Zip Code:</label>
</td>
<td>
<input id="zipcode" name="zipcode" placeholder="Zip Code" type="text" />
</td>
</tr>
</table>
</div>
<div ng-show="country==2">
<table>
<tr>
<td>
<label>Select Province: </label>
</td>
<td>
<select data-ng-model="state" data-ng-disabled="!states" data-ng-options="s.StateID as s.StateName for s in states" data-ng-change="GetRegion()">
<option value="">-- Select Province --</option>
</select>
</td>
</tr>
<tr>
<td>
<label>Select Region: </label>
</td>
<td>
<select data-ng-model="region" data-ng-disabled="!regions" data-ng-options="r.RegionID as r.RegionName for r in regions">
<option value="">-- Select Region --</option>
</select>
</td>
</tr>
<tr>
<td>
<label>Address:</label>
</td>
<td>
<input id="Address" name="Address" placeholder="Address" type="text" />
</td>
</tr>
<tr>
<td>
<label>Address 2:</label>
</td>
<td>
<input id="Address2" name="Address2" placeholder="Address 2" type="text" />
</td>
</tr>
<tr>
<td>
<label>City:</label>
</td>
<td>
<input id="city" name="city" placeholder="City" type="text" />
</td>
</tr>
<tr>
<td>
<label>Postal Code:</label>
</td>
<td>
<input id="postalcode" name="postalcode" placeholder="Postal Code" type="text" />
</td>
</tr>
</table>
</div>
</form>
</div>
</div>
</td>
<td>
<div>
<div>
<form name="mainForm" data-ng-submit="sendForm()" novalidate>
<div class="error">{{message}}</div>
<div>
<table>
<tr>
<td>
<label>Select Country: </label>
</td>
<td>
<select data-ng-model="country2" data-ng-options="c.CountryID as c.CountryName for c in countries" data-ng-change="GetShippingStates()">
<option value="">-- Select Country --</option>
</select>
</td>
</tr>
</table>
</div>
<div ng-show="country2==1">
<table>
<tr>
<td>
<label>Select State: </label>
</td>
<td>
<select data-ng-model="state2" data-ng-disabled="!states2" data-ng-options="s.StateID as s.StateName for s in states2" data-ng-change="GetShippingRegion()">
<option value="">-- Select State --</option>
</select>
</td>
</tr>
<tr>
<td>
<label>Select Region: </label>
</td>
<td>
<select data-ng-model="region2" data-ng-disabled="!regions2" data-ng-options="r.RegionID as r.RegionName for r in regions2">
<option value="">-- Select Region --</option>
</select>
</td>
</tr>
<tr>
<td>
<label>Address:</label>
</td>
<td>
<input id="Address" name="Address" placeholder="Address" type="text" />
</td>
</tr>
<tr>
<td>
<label>Address 2:</label>
</td>
<td>
<input id="Address2" name="Address2" placeholder="Address 2" type="text" />
</td>
</tr>
<tr>
<td>
<label>City:</label>
</td>
<td>
<input id="city" name="city" placeholder="City" type="text" />
</td>
</tr>
<tr>
<td>
<label>Zip Code:</label>
</td>
<td>
<input id="zipcode" name="zipcode" placeholder="Zip Code" type="text" />
</td>
</tr>
</table>
</div>
<div ng-show="country2==2">
<table>
<tr>
<td>
<label>Select Province: </label>
</td>
<td>
<select data-ng-model="state2" data-ng-disabled="!states2" data-ng-options="s.StateID as s.StateName for s in states2" data-ng-change="GetShippingRegion()">
<option value="">-- Select Province --</option>
</select>
</td>
</tr>
<tr>
<td>
<label>Select Region: </label>
</td>
<td>
<select data-ng-model="region2" data-ng-disabled="!regions2" data-ng-options="r.RegionID as r.RegionName for r in regions2">
<option value="">-- Select Region --</option>
</select>
</td>
</tr>
<tr>
<td>
<label>Address:</label>
</td>
<td>
<input id="Address" name="Address" placeholder="Address" type="text" />
</td>
</tr>
<tr>
<td>
<label>Address 2:</label>
</td>
<td>
<input id="Address2" name="Address2" placeholder="Address 2" type="text" />
</td>
</tr>
<tr>
<td>
<label>City:</label>
</td>
<td>
<input id="city" name="city" placeholder="City" type="text" />
</td>
</tr>
<tr>
<td>
<label>Postal Code:</label>
</td>
<td>
<input id="postalcode" name="postalcode" placeholder="Postal Code" type="text" />
</td>
</tr>
</table>
</div>
</form>
</div>
</div>
</td>
</tr>
</table>
</body>
</html>
New html to re-use directive:
#{
Layout = null;
}
<h2>Index</h2>
<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/cascade.js"></script>
<body ng-app="dropDown" ng-controller="DropDownController">
<dropdowndirective>
</dropdowndirective>
#*<div class="DropDownDirective"></div>
<div ng-DropDownDirective></div>*#
</body>
It looks like you have a syntax error in your directive where dropDownController should be a string like this:
app.directive('DropDownDirective', function () {
return {
restrict: 'E',
templateUrl: 'AddressControl',
controller: 'DropDownController',
replace:true,
}
});
Not sure why you wouldn't get an error message for that though...