here is the code
the view code:
<input type="text" class="form-control" ng-model="model.org" />
<input type="button" class="btn btn-primary" value="Load Repos" ng-click="getRepos(model.org)" ng-hide="model.repos" />
<div class="col-md-6">
<table class="table table-striped" ng-show="model.repos">
<tr>
<th>Name</th>
<th>Language</th>
<th></th>
</tr>
<tr ng-repeat="r in model.repos">
<td>
<h4>{{r.name}}</h4> {{r.description}}
</td>
<td>{{r.language}}</td>
<td><input type="button" class="btn btn-success" ng-click="loadDetail(r.name)" value="Detail"> </td>
</tr>
</table>
</div>
and this is the inside the controller:
$scope.model = {
number: 0,
result: 'Ready'
};
$scope.getRepos = getRepos;
function getRepos(org) {
$http.get('https://api.github.com/orgs/org/repos').then(function(response) {
$scope.model.repos = response.data;
}, function(response) {
alert(response.error);
$scope.model.repos = 'Error: ' + response.data.message;
})
}
when I click the button that has the ng-click="getRepos(javascript); I get undefined but if I copied this link https://api.github.com/orgs/javascript/repos to a browser it returns data!
what am I missing here?
I think you wanted to pass the parameter to getRepos in your GET url, like:
function getRepos(org) {
$http.get('https://api.github.com/orgs/' + org + '/repos').then(function(response) {
$scope.model.repos = response.data;
}, function(response) {
alert(response.error);
$scope.model.repos = 'Error: ' + response.data.message;
})
}
Related
how to loop the data from database my route in laravel is Route::get('api/contacts', [ContactController::class, 'index'])->name('contact.index'); and im trying to display all the list but im confuse with the js code someone expert here and please help me
class ContactController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$contacts = Contact::all();
// return view('contacts.index', compact('contacts'));
return response()->json(compact('contacts'));
}
<script>
import axios from "axios";
export default {
data() {
return {
form: {
first_name: "",
last_name: "",
email: "",
city: "",
country: "",
job_title: "",
},
errorMessage: "",
user: "",
};
},
methods: {
processCreate() {
this.errorMessage = "";
axios
.post("/api/contacts/index")
.then((response) => {})
.catch((error) => {
this.errorMessage = error.response.data.message;
console.log("error", error.response);
});
console.log(response);
},
},
mounted() {
// console.log(this.form)
},
};
</script>
<template>
<div class="row">
<div class="col-sm-12">
<h1 class="display-3">Contacts</h1>
<table class="table table-striped">
<thead>
<tr>
<td>ID</td>
<td>Name</td>
<td>Email</td>
<td>Job Title</td>
<td>City</td>
<td>Country</td>
<td colspan="3">Actions</td>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>
Show
</td>
<td>
Edit
</td>
<td>
<form method="post" action="">
<button class="btn btn-danger" type="submit">Delete</button>
</form>
</td>
</tr>
</tbody>
</table>
<div>
<router-link :to="{ name: 'contactsCreate' }">New Contact</router-link>
</div>
</div>
</div>
</template>
you should have a variable for your contacts in vuejs instance
like contacts : []
and when you return your data in controller with axios to vuejs, you have to set response to that variable:
.then(response => {
this.contacts = response.data;
}
)
and then wherever you want your data to be shown :
<tr v-for="item in this.contacts">
<td>#{{item .name}}</td>
<td>#{{item .subject}}</td>
</tr>
Step 1: Load data from rest api
methods: {
loadContactsFromAPI() {
var self = this;
return axios
.get("https://jsonplaceholder.typicode.com/users")
.then(function (response) {
self.contacts = response.data;
})
.catch(function (error) {
return error;
});
},
}
Step 2: Display the contact list to html template
<table class="table table-striped">
<thead>
<tr>
<td>ID</td>
<td>Name</td>
<td>Email</td>
<td>Job Title</td>
<td>City</td>
<td>Country</td>
<td colspan="3">Actions</td>
</tr>
</thead>
<tbody>
<tr :key="index" v-for="(contact, index) in contacts">
<td>{{ index + 1 }}</td>
<td>{{ contact.name }}</td>
<td>{{ contact.email }}</td>
<td>{{ contact.company.name }}</td>
<td>{{ contact.address.street }}</td>
<td>{{ contact.address.city }}</td>
<td>
Show
</td>
<td>
<a
href="#"
class="btn btn-primary"
#click.prevent="editContact(contact, index)"
>Edit</a
>
</td>
<td>
<button
class="btn btn-danger"
type="button"
#click="deleteContact(index)"
>
Delete
</button>
</td>
</tr>
</tbody>
</table>
Step 3: Implemented Edit or add new contact in html template
<div class="row" v-else-if="!showListContact">
<div>
<label>Name</label>
<input type="text" v-model="contact.name" />
</div>
<div>
<label>Email</label>
<input type="text" v-model="contact.email" />
</div>
<div>
<label>Job Title</label>
<input type="text" v-model="contact.company.name" />
</div>
<div>
<label>City</label>
<input type="text" v-model="contact.address.city" />
</div>
<div>
<button type="button" #click="saveContact">Save</button>
</div>
</div>
Step 4: Add Edit, Delete and Create new contact methods inside script
editContact(contact, index) {
this.showListContact = false;
this.selectedIndex = index;
this.contact = contact;
},
addNewContact() {
this.showListContact = false;
this.selectedIndex = "";
this.contact = {
company: {},
address: {},
};
},
saveContact() {
if (this.selectedIndex) {
this.contacts[this.selectedIndex] = this.contact;
} else {
this.contacts.push(this.contact);
}
// You have to make a call to backend api to save in db
this.showListContact = true;
},
deleteContact(index) {
if (confirm("Are you sure wants to delete the contact")) {
this.contacts.splice(index, 1);
// You have to make a call to backend api to delete in db
}
},
DEMO
For more details about Vue, Vuex, Form validations, Router, CRUD Operations, Table sorting, filtering refer the below project link
Complete Vue project with most of the features
I trying to consume wcf(Rest) Service in Angular JS Application. My Wcf service is working fine but when I run my Application in Google Chrome it is unable to get the data from database and I also can do insert , update and delete operation. When I run the application its do not show any error but when I lunch developer tools i see following this errors.
?o=3&g=EC0825C4-90A4-2692-D257-CD2C2B565912&s=1A2C77E8-0498-4A11-B8B8-D740DBEC71C4&z=1403834305:2 Uncaught SyntaxError: Unexpected token <
Index:1 XMLHttpRequest cannot load http://localhost:50028/StudentService.svc/GetAllStudent. Redirect from 'http://localhost:50028/StudentService.svc/GetAllStudent' to 'http://localhost:50028/StudentService.svc/GetAllStudent/' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header
Here is My Angular JS Code ...
/// <reference path="../angular.min.js" />
var app;
(function () {
app = angular.module("RESTClientModule", []);
app.controller("CRUD_AngularJs_RESTController", function ($scope, CRUD_AngularJs_RESTService) {
$scope.OperType = 1;
//1 Mean New Entry
GetAllRecords();
//To Get All Records
function GetAllRecords() {
var promiseGet = CRUD_AngularJs_RESTService.getAllStudent();
promiseGet.then(function (pl) { $scope.Students = pl.data },
function (errorPl) {
$log.error('Some Error in Getting Records.', errorPl);
});
}
//To Clear all input controls.
function ClearModels() {
$scope.OperType = 1;
$scope.StudentID = "";
$scope.Name = "";
$scope.Email = "";
$scope.Class = "";
$scope.EnrollYear = "";
$scope.City = "";
$scope.Country = "";
}
//To Create new record and Edit an existing Record.
$scope.save = function () {
var Student = {
Name: $scope.Name,
Email: $scope.Email,
Class: $scope.Class,
EnrollYear: $scope.EnrollYear,
City: $scope.City,
Country: $scope.Country
};
if ($scope.OperType === 1) {
var promisePost = CRUD_AngularJs_RESTService.post(Student);
promisePost.then(function (pl) {
$scope.StudentID = pl.data.StudentID;
GetAllRecords();
ClearModels();
}, function (err) {
console.log("Some error Occured" + err);
});
} else {
//Edit the record
debugger;
Student.StudentID = $scope.StudentID;
var promisePut = CRUD_AngularJs_RESTService.put($scope.StudentID, Student);
promisePut.then(function (pl) {
$scope.Message = "Student Updated Successfuly";
GetAllRecords();
ClearModels();
}, function (err) {
console.log("Some Error Occured." + err);
});
}
};
//To Get Student Detail on the Base of Student ID
$scope.get = function (Student) {
var promiseGetSingle = CRUD_AngularJs_RESTService.get(Student.StudentID);
promiseGetSingle.then(function (pl) {
var res = pl.data;
$scope.StudentID = res.StudentID;
$scope.Name = res.Name;
$scope.Email = res.Email;
$scope.Class = res.Class;
$scope.EnrollYear = res.EnrollYear;
$scope.City = res.City;
$scope.Country = res.Country;
$scope.OperType = 0;
},
function (errorPl) {
console.log('Some Error in Getting Details', errorPl);
});
}
//To Delete Record
$scope.delete = function (Student) {
var promiseDelete = CRUD_AngularJs_RESTService.delete(Student.StudentID);
promiseDelete.then(function (pl) {
$scope.Message = "Student Deleted Successfuly";
GetAllRecords();
ClearModels();
}, function (err) {
console.log("Some Error Occured." + err);
});
}
});
app.service("CRUD_AngularJs_RESTService", function ($http) {
//Create new record
this.post = function (Student) {
var request = $http({
method: "post",
url: "http://localhost:50028/StudentService.svc/AddNewStudent",
data: Student
});
return request;
}
//Update the Record
this.put = function (StudentID, Student) {
debugger;
var request = $http({
method: "put",
url: "http://localhost:50028/StudentService.svc/UpdateStudent",
data: Student
});
return request;
}
this.getAllStudent = function () {
return $http.get("http://localhost:50028/StudentService.svc/GetAllStudent");
};
//Get Single Records
this.get = function (StudentID) {
return $http.get("http://localhost:50028/StudentService.svc/GetStudentDetails/" + StudentID);
}
//Delete the Record
this.delete = function (StudentID) {
var request = $http({
method: "delete",
url: "http://localhost:50028/StudentService.svc/DeleteStudent/" + StudentID
});
return request;
}
});
})();
Here is HTML CODE ..
#{
Layout = null;
}
<!DOCTYPE html>
<html data-ng-app="RESTClientModule">
<head title="ASAS">
<title></title>
<script src="~/Scripts/angular.min.js"></script>
<script src="~/Scripts/MyScripts/Modules.js"></script>
</head>
<body>
<table id="tblContainer" data-ng-controller="CRUD_AngularJs_RESTController">
<tr>
<td>
<table style="border: solid 2px Green; padding: 5px;">
<tr style="height: 30px; background-color: skyblue; color: maroon;">
<th></th>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Class</th>
<th>Year</th>
<th>City</th>
<th>Country</th>
<th></th>
<th></th>
</tr>
<tbody data-ng-repeat="stud in Students">
<tr>
<td></td>
<td><span>{{stud.StudentID}}</span></td>
<td><span>{{stud.Name}}</span></td>
<td><span>{{stud.Email}}</span></td>
<td><span>{{stud.Class}}</span></td>
<td><span>{{stud.EnrollYear}}</span></td>
<td><span>{{stud.City}}</span></td>
<td><span>{{stud.Country}}</span></td>
<td>
<input type="button" id="Edit" value="Edit" data-ng-click="get(stud)" />
</td>
<td>
<input type="button" id="Delete" value="Delete" data-ng-click="delete(stud)" />
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<td>
<div style="color: red;">{{Message}}</div>
<table style="border: solid 4px Red; padding: 2px;">
<tr>
<td></td>
<td>
<span>Student ID</span>
</td>
<td>
<input type="text" id="StudentID" readonly="readonly" data-ng-model="StudentID" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Student Name</span>
</td>
<td>
<input type="text" id="sName" required data-ng-model="Name" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Email</span>
</td>
<td>
<input type="text" id="sEmail" required data-ng-model="Email" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Class</span>
</td>
<td>
<input type="text" id="sClass" required data-ng-model="Class" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Enrollement Year</span>
</td>
<td>
<input type="text" id="sEnrollYear" required data-ng-model="EnrollYear" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>City</span>
</td>
<td>
<input type="text" id="sCity" required data-ng-model="City" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Country</span>
</td>
<td>
<input type="text" id="sCountry" required data-ng-model="Country" />
</td>
</tr>
<tr>
<td></td>
<td></td>
<td>
<input type="button" id="save" value="Save" data-ng-click="save()" />
<input type="button" id="Clear" value="Clear" data-ng-click="clear()" />
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
Here is My Screen Shot When I run the Application..
Any help would be great for me .Thanks
How do you get the ng-click event to actually fire? I've tried everything to get this to work. I know the alert is working initially, but after the list is displayed, quite magically all the buttons fail to function.
Here is the display of the page (pre/post alert). I've verified that each button for details is getting a unique id. As you can see, I've also tried $parent (since some of the buttons are within a ng-repeat) as well as $rootscope to try to get things to execute (i.e. the detail buttons). It's almost as if, after the initially display, the page has lost the reference to the angularjs file since nothing functions:
When page is first displayed
After getting the data
Here's the AngularJS file:
var app = angular.module("EmployeeApplication", [])
.controller("EmployeeController",
function ($scope, $http,$window) {
AngularInit();
function AngularInit() {
//This will be called once per form load, via the ng-load function on the div
$scope.name = '';
$scope.gender = '';
$scope.salary = '';
$scope.id = '';
$scope.DisplayAction = 'Unknown';
$scope.gotdata = false;
DisplayList();
ShowAlert('test')
}
function GetAllEmployees($http) {
//$scope.Message = 'NULL';
//$scope.employees = {};
$http.get('http://localhost:65315/api/employee').then(function (response) {
$scope.employees = response.data;
$scope.Message = 'OK';
$scope.gotdata = true;
},
function (err) {
$scope.Message = 'Call failed' + err.status + ' ' + err.statusText;
$scope.employees = {};
$scope.gotdata = false;
}
);
//window.setTimeout(function () {
// $scope.gotdata = true;
//}, 1000);
};
function DisplayList() {
//call the web service to get the list of people
//set the display action so that the list will be displayed
GetAllEmployees($http)
$scope.DisplayAction = 'List';
};
function CreateNewEmployee() {
$scope.name = '';
$scope.gender = '';
$scope.salary = '';
$scope.id = '';
$scope.DisplayAction = 'Create';
$scope.$apply();
};
function ShowDetails(id) {
//call the web service to get the details of the person
ShowAlert('test')
$scope.gotdata = false;
$http.get('http://localhost:65315/api/employee/' + id).then(function (response) {
$scope.employees = response.data;
$scope.DisplayAction = 'Details';
$scope.Message = 'OK';
},
function (err) {
$scope.Message = 'Call failed' + err.status + ' ' + err.statusText;
$scope.employees = {};
}
);
//Set the $scope.CurrentEmployee
$scope.$apply();
};
function ShowAlert(msg)
{
$window.alert(msg);
}
function CreateEmployee() {
//perform the actual creation based on $scope.CurrentEmployee
//if successful
DisplayList();
};
function DeleteEmployee(id) {
$scope.DisplayAction = 'Delete';
$scope.$apply();
};
function DoDeleteEmployee(id) {
//Perform actual deletion
//if successful
DisplayList();
};
function EditEmployee(id) {
//get the employee based on ID
$scope.DisplayAction = 'Edit';
$scope.$apply();
};
function EditUpdate() {
//perform the actual update based on $scope.id
//if successful
DisplayList();
};
}
);
//angular.module('EmployeeApplication', [])
// .controller('EmployeeController', ['$scope', '$window', function ($scope, $window) {
// $scope.greeting = 'Hello, World!';
// $scope.doGreeting = function (greeting) {
// $window.alert(greeting);
// };
// }]);
var app = angular.module("MyModule", []).controller("MyController", function ($scope, $http)
{
$scope.MadeItHereMessage = 'We made it to the controller (first controller)';
$scope.employees = {};
$http.get('http://localhost:65315/api/employee').then(function (response) {
$scope.employees = response.data;
$scope.Message = "OK";
},
function (err)
{
$scope.Message = "Call failed" + err.status + " " + err.statusText;
}
);
});
//var app = angular.module("MyModule", []).controller("MyController", function initController($scope)
//{
// $scope.MadeItHereMessage = 'This is a loadtest';
//});
//var app = angular.module("EmployeeApplication", ['$rootscope','$scope','$http'])
//.controller("EmployeeController",
// function AppCtrl($rootscope,$scope, $http)
// {
// $scope.DisplayAction = "List";
// }
//);
//var app = angular.module("MyModule", []).controller("MyController", function ($scope, $http) {
// $http.get('EmployeeWebService.asmx/GetAllEmployees').then(function (response) {
// $scope.employees = response.data;
// }
// );
//});
Here is the HTML file:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="Scripts/angular.js"></script>
<script src="Scripts/EmployeeAngular.js"></script>
<meta charset="utf-8" />
</head>
<body ng-app="EmployeeApplication">
<div ng-controller="EmployeeController" ng-init="AngularInit()">
{{Message}}
<br/>
{{DisplayAction}}
<button id="btnCreateNew1" ng-click="$parent.ShowAlert('Parent scope button pressed')">Show message from parent scope</button>
<br />
<!--The following is for listing the entire list of employees-->
<div id="listSection" ng-show="DisplayAction=='List'">
<!--The employees data is: {{employees}}-->
<!--<div id="listSection">-->
<table>
<thead>List of defined Employees</thead>
<tr>
<!--<td><button id="btnCreateNew" ng-click="CreateNewEmployee()">Create Employee</button></td>-->
<td><button id="btnCreateNew" ng-click="$rootscope.ShowAlert('Create button pressed')">Create Employee</button></td>
</tr>
<tr>
<td ng-show="gotdata">
<table id="EmployeeList">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Gender</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="employee in employees" ng-if="employees && employees!={undefined}">
<td>{{employee.id}}</td>
<td>{{employee.name}}</td>
<td>{{employee.gender}}</td>
<td>{{employee.salary}}</td>
<td><button id="btnDetailsA{{employee.id}}" ng-click="$parent.ShowDetails({{employee.id}})">Details</button></td>
<td><button id="btnDetailsB{{employee.id}}" ng-click="$parent.ShowDetails({{employee.id}})">Details B</button></td>
<td><button id="btnDetailsC{{employee.id}}" ng-click="ShowDetails({{employee.id}})">Details C</button></td>
<td><button id="btnDetailsD{{employee.id}}" ng-click="$scope.ShowDetails({{employee.id}})">Details D</button></td>
<td><button id="btnDetailsE{{employee.id}}" ng-click="$rootscope.ShowDetails({{employee.id}})">Details E</button></td>
<td><button id="btnDelete{{employee.id}}" ng-click="$parent.DeleteEmployee({{employee.id}})">Delete</button></td>
<td><button id="btnEdit{{employee.id}}" ng-click="$parent.EditEmployee({{employee.id}})">Edit</button></td>
</tr>
</tbody>
</table>
</td>
</tr>
</table>
</div>
<!--The following is for listing the details of a single employee-->
<div id="DetailsSection" ng-show="DisplayAction=='Details'">
<table>
<tr>
<td>ID:</td>
<td> <input id="DetailsID" value={{employee.id}} /></td>
</tr>
<tr>
<td>Name:</td>
<td><input id="DetailsName" value={{employee.name}} /> </td>
</tr>
<tr>
<td>Gender:</td>
<td><input id="DetailsGender" value={{employee.gender}} /> </td>
</tr>
<tr>
<td>Salary:</td>
<td><input id="DetailsSalary" value={{employee.salary}} /> </td>
</tr>
<tr>
<td>
<button id="NavTolist" ng-click="DisplayList()">Back to List</button>
</td>
<td>
<button id="NavToDelete" ng-click="DeleteEmployee({{id}})">Delete</button>
</td>
<td>
<button id="NavToEdit" ng-click="EditEmployee({{id}})">Edit</button>
</td>
</tr>
</table>
</div>
<!--The following is for editing a employee-->
<!--<div id="EditSection" ng-show="DisplayAction=='Edit'">
<table>
<tr>
<td>ID:</td>
<td>
<input id="ID" value={{id}} />
</td>
</tr>
<tr>
<td>Name:</td>
<td><input id="" value={{name}} ng-bind="name" /> </td>
</tr>
<tr>
<td>Gender:</td>
<td><input id="" value={{gender}} ng-bind="gender" /> </td>
</tr>
<tr>
<td>Salary:</td>
<td><input id="" value={{salary}} ng-bind="salary" /> </td>
</tr>
<tr>
<td>
<button id="EditUpdate" type="button" value="Update" ng-click="EditUpdate()"></button>
</td>
<td>
<button id="NavTolistEdit" type="button" value="Back to List" ng-click="DisplayList()"></button>
</td>
<td>
<button id="NavToDeleteEdit" type="button" value="Delete" ng-click="DeleteEmployee({{id}})"></button>
</td>
</tr>
</table>
</div>-->
<!--The following is for verification of deletion-->
<div id="DeletionSection" ng-show="DisplayAction=='Delete'">
<table>
<tr>
<td>Do you really want to delete {{name}}</td>
<td></td>
<td>
<button id="btnCancelDelete" type="button" value="No" ng-click="DisplayList()"></button>
</td>
<td>
<button id="btnDeleteEmployee" type="button" value="Yes" ng-click="DoDeleteEmployee({{id}})"></button>
</td>
</tr>
</table>
</div>
<!--The following is for creation of a employee-->
<!--<div id="CreationSection" ng-show="DisplayAction=='Create'">
<table>
<tr>
<td>Name:</td>
<td><input id="" value="" ng-bind="name" /> </td>
</tr>
<tr>
<td>Gender:</td>
<td><input id="" value="" ng-bind="gender" /> </td>
</tr>
<tr>
<td>Salary:</td>
<td><input id="" value="" ng-bind="salary" /> </td>
</tr>
<tr>
<td>
<button id="btnCreateEmployee" type="button" value="Delete" ng-click="CreateEmployee()"></button>
</td>
<td>
<button id="NavTolistEdit" type="button" value="Back to List" ng-click="DisplayList()"></button>
</td>
</tr>
</table>
</div>-->
</div>
</body>
</html>
unlike vanilla event handlers, ng-click will look for a event handler in the controller scope, so when you have:
<button id="NavTolist" ng-click="DisplayList()">Back to List</button>
your controller must have:
$scope.DisplayList = function() {
//call the web service to get the list of people
//set the display action so that the list will be displayed
GetAllEmployees($http)
$scope.DisplayAction = 'List';
};
you might be interested in take a look in a few sample projects over the web in order to better organize your code.
on a side note, whenever possible sample your web-capable code on plunker / jsfiddle / codepen, since it provides a huge help for anyone willing to help.
When i get GetAll(); angular function to refresh the table it called Because i get the alert message but it doesn't refresh the table.
I am new in AngularJS and i don't know how to solve that problem
Please help me
Here is my code:
[HttpGet]
public JsonResult GetAllContinents()
{
MyDatabaseEntities db = new MyDatabaseEntities();
var Result = (from con in db.Continents select new { ContinentId = con.ContinentId, ContinentName = con.ContinentName.Trim() }).ToList();
return Json(Result, JsonRequestBehavior.AllowGet);
}
HTML:
<div data-ng-controller="myCntrl">
<div class="col-md-12">
<table class="table table-bordered table-hover" style="width:800px">
<thead>
<tr>
<th><b></b>ID<b></b></th>
<th>continent Name</th>
<th>Modify</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="con in ContinentsList">
<td>{{con.ContinentId}}</td>
<td>{{con.ContinentName}}</td>
<td>
<button class="btn btn-md glyphicon glyphicon-trash"
title="Click here to delete record" />
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div data-ng-controller="myCntrl">
Enter Continent Name: <input type="text" ng-model="Continent.ContinentName" />
<input type="button" value="Add" ng-click="AddContinent()" />
</div>
AngularJs:
app.controller("myCntrl", function ($scope, $http, angularService) {
$scope.GetAll = function () {
$scope.ContinentsList = [];
$http.get('/Home/GetAllContinents')
.success(function (data) {
$scope.ContinentsList = data;
alert('Done!')
})
.error(function (msg) {
alert(msg);
})
};
$scope.GetAll();
$scope.AddContinent = function () {
$http.post('/Home/AddContinent', { Con: $scope.Continent })
.success(function (data) {
$scope.clear();
$scope.GetAll();
})
.error(function (msg) {
alert(msg)
})
};`enter code here`
Thank you in advance
You have to define the Continental ist ouside the function scope.
$scope.ContinentsList = [];
function getAll () {
$http.get('/Home/GetAllContinents')
.success(function (data) {
$scope.ContinentsList = data;
alert('Done!')
})
.error(function (msg) {
alert(msg);
})
};
Remove ng-controller from :
<div data-ng-controller="myCntrl">
Enter Continent Name: <input type="text" ng-model="Continent.ContinentName" />
<input type="button" value="Add" ng-click="AddContinent()" />
</div>
Now you have two scope and two lists of content and it's problem. In one scope you have a list that you show on view and in second scope you add elements and try refresh lists.
This is working code:
<div data-ng-controller="myCntrl">
<div class="col-md-12">
<table class="table table-bordered table-hover" style="width:800px">
<thead>
<tr>
<th><b></b>ID<b></b></th>
<th>continent Name</th>
<th>Modify</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="con in ContinentsList">
<td>{{con.ContinentId}}</td>
<td>{{con.ContinentName}}</td>
<td>
<button class="btn btn-md glyphicon glyphicon-trash"
title="Click here to delete record" />
</td>
</tr>
</tbody>
</table>
</div>
Enter Continent Name: <input type="text" ng-model="Continent.ContinentName" />
<input type="button" value="Add" ng-click="AddContinent()" />
</div>
I have been at this for awhile now but in short I am making a UI that allows our users to modify a MySQL DB using an Angular frontend and Slim PHP to serve up the REST.
I continue to get an error stating that 'firstName' is not defined as a column and I cant seem to figure out why. I believe it has something to do with the way the ng-repeat works and how I can assign / call objects inside of it but I am stuck!
Here is the HTML, App.js and index.php - The code is a little hacked up but I want to edit the rows in-line.
Any knowledge is much appreciated as I have just started using Angular and REST this year!
List.html
<div class="row">
<div class="col-lg-12">
<table class="table table-hover">
<thead>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
<th>Address 1</th>
<th>Address 2</th>
<th>City</th>
<th>State</th>
<th>Zip</th>
<th class="text-center">Edit</th>
</tr>
</thead>
<tbody ng-repeat="referral in referrals | filter:query | limitTo:limitBy | orderBy:lastName">
<tr >
<td>{{referral.ID}}</td>
<td>
<!-- <span id="firstName" data-ng-hide="editMode">{{referral.firstName}}</span>-->
<span data-ng-hide="editMode">{{referral.firstName}}</span>
<input type="text" data-ng-show="editMode" ng-model="referral.firstName"/>
</td>
<td>
<span data-ng-hide="editMode">{{referral.lastName}}</span>
<input type="text" data-ng-show="editMode" ng-model="referral.lastName"/>
</td>
<td>
<span data-ng-hide="editMode">{{referral.address1}}</span>
<input type="text" data-ng-show="editMode" data-ng-model="referral.address1"/>
</td>
<td>
<span data-ng-hide="editMode">{{referral.address2}}</span>
<input type="text" data-ng-show="editMode" data-ng-model="referral.address2"/>
</td>
<td>
<span data-ng-hide="editMode">{{referral.city}}</span>
<input type="text" data-ng-show="editMode" data-ng-model="referral.city"/>
</td>
<td>
<span data-ng-hide="editMode">{{referral.state}}</span>
<input type="text" data-ng-show="editMode" data-ng-model="referral.state"/>
</td>
<td>
<span data-ng-hide="editMode">{{referral.zipCode}}</span>
<input type="text" data-ng-show="editMode" data-ng-model="referral.zipCode"/>
</td>
<td class="text-center">
<button type="submit" data-ng-hide="editMode" data-ng-click="editMode = true; editAppKey(entry)" class="btn btn-default">Edit</button>
<button type="submit" data-ng-show="editMode" data-ng-click="editMode = false; saveField(referral)" class="btn btn-default">Save</button>
<button type="submit" data-ng-show="editMode" data-ng-click="editMode = false; cancel()" class="btn btn-default">Cancel</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
App.js
app.controller('viewController', function($resource, $scope, $location, $route, $routeParams) {
$scope.title = 'Endo Admin';
$scope.query = {};
$scope.queryBy = 'lastName';
$scope.limitBy = '50';
var Referrals = $resource('http://pdgrosit02v/endoAdmin/app/api/referrals');
$scope.referrals = Referrals.query();
$scope.newField = {};
$scope.editing = false;
$scope.editAppKey = function(field) {
$scope.editing = $scope.referrals.indexOf(field);
$scope.newField = angular.copy(field);
}
$scope.saveField = function(index) {
// if ($scope.editing !== false) {
// var Referral = $resource(('http://pdgrosit02v/endoAdmin/app/api/referral/'+ index.ID));
//
// $scope.referral = Referral.get();
//
$scope.referral = $scope.newField;
// $scope.editing = false;
var ReferralPut = $resource(('http://pdgrosit02v/endoAdmin/app/api/referral/'+ index.ID), {}, { update: { method: 'PUT'}} );
ReferralPut.update($scope.referral, function() {
// success
$location.path('/endoadmin');
}, function() {
// error
console.log(error);
});
};
});
index.php
<?php
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
use Slim\Slim;
$app = new Slim();
$app->get('/referrals', 'getReferrals');
$app->get('/referral/:id', 'getReferral');
$app->put('/referral/:id', 'updateReferral');
$app->run();
function updateReferral($id) {
$referral = Slim::getInstance()->request()->getBody();
$data = json_decode($referral, true);
$sql = "UPDATE endo_referral SET firstName=:first_Name, lastName=:last_Name WHERE ID=$id";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindValue(":first_Name", $data['firstName']);
$stmt->bindValue(":last_Name", $data['lastName']);
$stmt->execute();
$db = null;
echo json_encode($data);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
In the $scope.saveField function, you should use the passed-in referral. Instead of
...
ReferralPut.update($scope.referral, function() {
// success
$location.path('/endoadmin');
}, function() {
// error
console.log(error);
});
...
Looking at your code, it looks like this needs to be:
ReferralPut.update(index, function() {
// success
$location.path('/endoadmin');
}, function() {
// error
console.log(error);
});
The $scope.saveField function is passed the current referral in the index field. $scope.referral is undefined in the saveField function.
There may be other issues, but this was the one that stood out the most.