What is wrong in the following angularjs code - angularjs

What is wrong in my code? it is not working properly
My .html page looks like
I am a beginner level coder and have below codes:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="ISO-8859-1">
<title>Index</title>
<script type="text/javascript" src="/scripts/angular.js"></script>
<script type="text/javascript">
alert("in script");
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope , $http) {
refreshData();
function refreshData(){
alert("function called");
$http({
alert("get all countries");
method: 'GET',
url:'http://localhost:8081/SpringWithAngularJs/rest/countries.json'
}).success(function(data)
{
$scope.posts = data;
});
}
$scope.form = {
countryName : "pp",
population : "1000"
};
$scope.add=function(){
$http({
alert("add countries");
method: 'POST',
url:'http://localhost:8081/SpringWithAngularJs/rest/countries/create/'+$scope.form.countryName+'/'+$scope.form.population
}).success(function(data){
alert("Country Added");
refreshData();
});
}
$scope.remove=function(data){
$http({
alert("delete countries");
method: 'DELETE',
url:'http://localhost:8081/SpringWithAngularJs/rest/countries/delete/'+data
}).success(function(data){
alert('Country Deleted');
refreshData();
});
}
});
</script>
</head>
<body ng-controller="myCtrl">
<h1>Country List</h1>
<table border="">
<thead>
<tr>
<th>Country Id</th>
<th>Country Name</th>
<th>Country Population</th>
<th>Action</th>
</tr>
</thead>
<tr ng-repeat="c in posts">
<td>{{c.countryId}}</td>
<td>{{c.countryName}}</td>
<td>{{c.population}}</td>
<td><button ng-click="remove{$index}">Remove</button></td>
</tr>
</table>
<h1>Add Country</h1>
<table>
<tr>
<td>Country Name:</td>
<td><input type="text" ng-model="form.countryName"/></td>
</tr>
<tr>
<td>Country Population:</td>
<td><input type="text" ng-model="form.population"/></td>
</tr>
<tr>
<td><button type="submit" ng-click="add()">Add</button></td>
</tr>
</table>
</body>
</html>
my controller looks like:
When running the html page not even alert functions of javascript is working.
why this is happening?
package com.cg.springwithangularjs.controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.cg.springwithangularjs.dtos.Country;
import com.cg.springwithangularjs.exceptions.CountryException;
import com.cg.springwithangularjs.services.CountryService;
#RestController
public class CountryFrontController {
#Autowired
CountryService countryService;
#RequestMapping(value="/countries",method=RequestMethod.GET,headers="Accept=application/json")
public List<Country> getallCountries(Model model){
System.out.println("in function");
try {
return countryService.getAllCountries();
} catch (CountryException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#RequestMapping(value="/countries/create/{name}/{popu}",method=RequestMethod.POST,headers="Accept=application/json")
public List<Country> addCountry(#PathVariable String name , #PathVariable String popu){
Country country = new Country();
country.setCountryName(name);
country.setPopulation(popu);
try {
countryService.addCountry(country);
return countryService.getAllCountries();
} catch (CountryException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#RequestMapping(value="/countries/delete/{id}",method=RequestMethod.DELETE,headers="Accept=application/json")
public List<Country> deleteCountry(#PathVariable String id){
try {
countryService.delete(id);
return countryService.getAllCountries();
} catch (CountryException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}

Remove the alert() from the configuration object in your three $http services, so that they look like
$http({method: 'GET', url: '/someUrl'}).success ...
Also try and change the remove function call from:
<td><button ng-click="remove{$index}">Remove</button></td>
to:
<td><button ng-click="remove($index)">Remove</button></td>

Related

The value is not updating dynamically until refresh button is clicked-Spring+Angular

It's Spring+Angular CURD app. Problem is whenever a user enters the details and hit submit button the records are successfully getting inserted into dB tables but the view is not updating with an extra row(new data) until the refresh button is clicked.
After refreshing the page it's successfully showing all the records.
But it should show the data dynamically
And it works fine for delete option whenever delete button is clicked it's deleting a row from view page(table) and db Table too.
MyController
-----------------
#RestController
public class HomeController {
#Autowired
private UserService service;
#RequestMapping(value="/home")
public ModelAndView getHomePage() {
return new ModelAndView("home");
}
#RequestMapping(value="/add",method=RequestMethod.POST,consumes=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Void> addUser(#RequestBody UserCommand user){
int result= 0;
UserDto dto= null;
dto= new UserDto();
BeanUtils.copyProperties(user, dto);
result= service.processUser(dto);
if(result!=0) {
return new ResponseEntity<>(HttpStatus.OK);
}
return new ResponseEntity<Void>(HttpStatus.CONFLICT);
}
#RequestMapping(value="/userDetails",produces="application/json",method=RequestMethod.GET)
public List<UserDto> getAllUsers(){
List<UserDto> listDto= null;
listDto= service.retrieveAllUsers();
return listDto;
}
#RequestMapping(value="/deleteUser",method=RequestMethod.DELETE,consumes=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Void> deleteAUser(#RequestBody UserCommand cmd){
int result= 0;
result= service.deleteUser(cmd.getEmail());
if(result!=0) {
return new ResponseEntity<Void>(HttpStatus.OK);
}
return new ResponseEntity<>(HttpStatus.CONFLICT);
}
}
Home.jsp
------------
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Home | Page</title>
<link rel="stylesheet" href='<c:url value="/main.css"></c:url>'/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script type="text/javascript">
var app= angular.module("myApp",[]);
app.controller("HomeController",function($scope,$http){
$scope.users=[];
$scope.userform={
name: "",
email: "",
mobile: ""
};
getUserDetails();
function getUserDetails(){ //this method
$http({
method: 'GET',
url: 'userDetails',
}).then(function successCallback(response){
$scope.users= response.data;
},function errorCallback(response){
alert(response.statusText);
});
}
$scope.addUser= function(){ //Problem Lies Here
$http({
method: 'POST',
url: 'add',
data: angular.toJson($scope.userform),
headers: {
'Content-Type' : 'application/json'
}
}).then(getUserDetails(),clearForm()); //it's calling above function to get the updated data
} //------------------------------------
function clearForm(){
$scope.userform.name="";
$scope.userform.email="";
$scope.userform.mobile="";
document.getElementById("name").disabled= false;
}
$scope.deleteUser= function(user){
$http({
method: 'DELETE',
url: 'deleteUser',
data: angular.toJson(user),
headers: {
'Content-Type': 'application/json'
}
}).then(getUserDetails());
}
});
</script>
</head>
<body ng-app="myApp" ng-controller="HomeController">
<h1>Spring+Angular CURD Application</h1>
<form method="post">
<table cellpadding="0" cellspacing="0" align="center" width="500px">
<tr>
<td>Name:</td>
<td><input type="text" id="name" ng-model="userform.name"></td>
</tr>
<tr><td> </td></tr>
<tr>
<td>Email:</td>
<td><input type="text" id="email" ng-model="userform.email"></td>
</tr>
<tr><td> </td></tr>
<tr>
<td>Mobile:</td>
<td><input type="text" id="mobile" ng-model="userform.mobile"></td>
</tr>
<tr><td> </td></tr>
<table align="center" cellpadding="0" cellspacing="0" width="200px">
<tr>
<td><input type="submit" ng-click="addUser()" value="Add"></td>
</tr>
</table>
</table>
</form>
<h2>Registered User's</h2>
<table align="center" cellpadding="0" cellspacing="0" border="1" width="600px">
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Mobile</th>
<th>Operation's</th>
</tr>
<tr ng-repeat="user in users">
<td>{{user.id}}</td>
<td>{{user.name}}</td>
<td>{{user.email}}</td>
<td>{{user.mobile}}</td>
<td>
<button ng-click="deleteUser(user)">Delete</button> |
<button ng-click="editUser(user)">Edit</button>
</td>
</tr>
</table>
</body>
</html>
Try changing function then callback as:
$scope.addUser = function() {
$http({
method: 'POST',
url: 'add',
data: angular.toJson($scope.userform),
headers: {
'Content-Type' : 'application/json'
}
}).then(function successCallback(response) {
getUserDetails();
clearForm());
})
}
As you use it in function getUserDetails().

Displaying data using AngularJS

I am trying to represent some data taken from database in a table. I am using jersey as back-end and I have tested it in Postman that it works. The problem is I cannot display my data in the table in front-end, when I use AngularJS. It only shows me a blank table, without data at all. I am pretty new to AngularJS and I really want anyone of you to help me find the problem with my piece of code below.
list_main.js
angular.module('app', [])
.controller('ctrl', function($scope, $http){
$scope.bookList = [];
$scope.loadData = function(){
$http.get('http://localhost:8080/BookCommerce/webapi/list').then(function(data){
$scope.bookList = data;
console.log($scope.bookList);
})
}
$scope.loadData();
})
index2.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>List Of Books</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></s‌​cript>
<script src="js/list_main.js"></script>
</head>
<body>
<div class="row" data-ng-controller="ctrl" data-ng-app="app" data-ng-init="loadData()" style="margin: 10px;">
<div class="col-md-7">
<div class="panel panel-primary">
<table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered" id="exampleone">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Author</th>
<th>Description</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="book in bookList">
<td>{{book.book_id}}</td>
<td>{{book.book_title}}</td>
<td>{{book.book_author}}</td>
<td>{{book.book_description}}</td>
<td>{{book.book_price}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
ListDAO.java
public class ListDAO {
public List<Book> findAll() {
List<Book> list = new ArrayList<Book>();
Connection c = null;
String sql = "SELECT * FROM book";
try {
c = ConnectionHelper.getConnection();
Statement s = c.createStatement();
ResultSet rs = s.executeQuery(sql);
while (rs.next()) {
list.add(processRow(rs));
}
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
ConnectionHelper.close(c);
}
return list;
}
protected Book processRow(ResultSet rs) throws SQLException {
Book book = new Book();
book.setBook_id(rs.getInt("book_id"));
book.setBook_title(rs.getString("book_title"));
book.setBook_author(rs.getString("book_author"));
book.setBook_description(rs.getString("book_description"));
book.setBook_price(rs.getInt("book_price"));
return book;
}
}
ListResource.java
#Path("/list")
public class ListResource {
ListDAO dao=new ListDAO();
#GET
#Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public List<Book> findAll() {
System.out.println("findAll");
return dao.findAll();
}
}
Please help me. Thank you!
Okay this is much better than the last time,
There's still some bits wrong with your JS - it should look like this :
// Code goes here
var baseUrl = "https://demo5019544.mockable.io/";
angular.module('app', [])
.controller('ctrl', function($scope, $http){
$scope.bookList = [];
$scope.loadData = function(){
$http.get(baseUrl + 'BookCommerce/webapi/list').then(function(data){
$scope.bookList = data.data;
})
}
})
I made a demo REST service at : https://demo5019544.mockable.io/BookCommerce/webapi/list
which produces the kind of output your web service should product, I tested the code with this web service and with the tweaks I made it worked -- Yay.
The last thing I'd do now is check that your web service is throwing out the same / similar output that my mock is producing.

Trying to populate data in ASP.Net controller and fetch it view using angularjs

I am trying to populate data through controller and display it in view using angular js. I am using a function to return JSON data and use the data in the view.However i am not getting the data due to some error.
Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Angular4DotnetMvc.Controllers
{
public class CourseController : Controller
{
// GET: Course
public ActionResult Index()
{
return View("Index","",GetCourses());
}
private object GetCourses()
{
var courses = new []{
new CourseVm {Number = "1", Name = "Science", Instructor= "Sai"},
new CourseVm {Number = "2", Name = "Geography", Instructor= "Ram"}
};
var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver()};
return JsonConvert.SerializeObject(courses, Formatting.None, settings);
}
}
public class CourseVm
{
public string Number { get; set; }
public string Name { get; set; }
public string Instructor { get; set; }
}
}
Index.cshtml
#model string
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="container" ng-app>
<div class="row">
<table class="table table-condensed table-hover">
<tr ng-init="courses = #Html.Raw(Model)">
<th>Course</th>
<th>Course Name</th>
<th>Instructors</th>
</tr>
<tr ng-repeat="course in courses">
<td>{{course.Number}}</td>
<td>{{course.Name}}</td>
<td>{{course.Instructor}}</td>
</tr>
</table>
</div>
</div>
Layout.cshtml
<html>
<head>
<title>Angular4DotNet</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<script src="~/Scripts/jQuery/jquery-3.1.1.min.js"></script>
<script src="~/Scripts/bootstrap/bootstrap.js"></script>
<link href="~/Scripts/bootstrap/bootstrap.min.css" rel="stylesheet" />
<link href="~/Scripts/bootstrap/bootstrap.css" rel="stylesheet" />
#RenderSection("JavaScriptInHeader",required:false)
</head>
<body ng-app>
#RenderBody()
</body>
</html>
I am getting the following error:
Error: [$parse:ueoe] http://errors.angularjs.org/1.6.1/$parse/ueoe?p0=courses%20%3D%20%5B%7B
Why the data binding not happening?
The error is :
I am not sure why ="" after "instructor":"ram"}] is being added in the end in #Html.Raw(Model). i believe because of this it fails and agular cannot parse.
I would do on this way:
Create an action just to return the json content:
// GET: Course
public ActionResult Index()
{
return View();
}
public ActionResult GetCourses()
{
var courses = new []{
new CourseVm {Number = "1", Name = "Science", Instructor= "Sai"},
new CourseVm {Number = "2", Name = "Geography", Instructor= "Ram"}
};
return Json(courses, JsonRequestBehavior.AllowGet)
}
Then create an Angular controller:
angular.module('yourApp').controller('CoursesCtrl', ['$scope',function($scope)
{
$scope.courses = [];
$scope.loadCourses = function () {
$http.get('/Course/GetCourses').then(function (response) {
$scope.courses = response.data;
}, function (data) {
//error
});
}
}]);
After that insert the controller in the view:
<div class="container" ng-app="yourApp">
<div ng-controller="CoursesCtrl">
<div class="row">
<table class="table table-condensed table-hover" data-ng-init="loadCourses();">
<tr>
<th>Course</th>
<th>Course Name</th>
<th>Instructors</th>
</tr>
<tr ng-repeat="course in courses">
<td>{{course.Number}}</td>
<td>{{course.Name}}</td>
<td>{{course.Instructor}}</td>
</tr>
</table>
</div>
</div>
</div>
I hope this can help you.

Binding Viewbag Data to Angular JS

I have a List in my controller which is being of type Student(class in the model)
public class DefaultController : Controller
{
// GET: Default
public ActionResult Index()
{
List<Student> obj = new List<Student>() {
new Student() { ID=1,Name="titi",Address="bbsr"},
new Student() { ID=1,Name="titi1",Address="bbsr"},
new Student() { ID=1,Name="titi2",Address="bbsr"}
};
ViewBag.data = obj;
return View();
}
}
I am using Angular JS (Beginner to Angular JS)
<html>
<head>
<title>Index</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body ng-app="EFView">
#{ var a = ViewBag.data;}
<div ng-init="init(#Html.Raw(a)">
<table>
<tr ng-repeat="x in a">
<td >
{{x.ID}}
</td>
<td>
{{x.Name}}
</td>
<td>
{{x.Address}}
</td>
</tr>
</table>
</div>
</body>
</html>
Not getting the output as expected.. where & what I am missing, I tried with all trial

Ajax function not calling

I am trying to call web service using ajax call in AngularJS Application and want to display data. But its not reaching to function. what is the problem.
AJAX Call-
function EmpCtrl($scope) {
$scope.getEmployee = function () {
$.ajax({
type: "POST",
url: "EmpWebService.asmx/GetEmployee",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$(msg).find('Table').each(function (i, row) {
$scope.Name = $(row).find('empName').text();
$scope.Age = $(row).find('empAge').text();
$scope.City = $(row).find('empCity').text();
});
}
});
};
}
Here is my web service
[WebMethod]
public static string GetEmployee()
{
string connectionStr = ConfigurationManager.ConnectionStrings["connectionStr"].ConnectionString;
SqlConnection con = new SqlConnection(connectionStr);
SqlCommand cmd;
DataTable dt;
try
{
con.Open();
cmd = con.CreateCommand();
cmd.CommandText = "select * from Emp_TempTbl";
using(SqlDataAdapter sda=new SqlDataAdapter (cmd))
{
using (DataSet ds=new DataSet ())
{
sda.Fill(ds);
return ds.GetXml();
}
}
}
catch(Exception)
{
throw;
}
And here is Angular JS UI
<html xmlns="http://www.w3.org/1999/xhtml" ng-app="myApp">
<head runat="server">
<title></title>
<script src="Scripts/angular.js"></script>
<script src="Scripts/jquery-1.8.3.min.js"></script>
<script src="script.js"></script>
<script>
angular.module('myApp', [])
.controller('EmpCtrl', EmpCtrl);
</script>
</head>
<body>
<form id="form1" ng-controller="EmpCtrl" ng-submit="save()">
<div style="font-family: Verdana; font-size: 12px; margin-left: 450px;">
<div>
<input type="button" id="btnFetch" value="Fetch" ng-click="getEmployee()" />
</div>
</div>
<hr />
<table border="1" style="text-align: center; margin-left: 410px;">
<tr>
<td> Name
</td>
<td> Age
</td>
<td>City
</td>
</tr>
<tr>
<td>{{Name}}
</td>
<td>{{Age}}
</td>
<td>{{City}}
</td>
</tr>
</table>
</form>
</body>
</html>
Change controller to :
function EmpCtrl($scope, $http) {
var post_data = {};
var responsePromise = $http.post("EmpWebService.asmx/GetEmployee", post_data);
responsePromise.success(function(msg, status1, headers, config) {
$(msg).find('Table').each(function (i, row) {
$scope.Name = $(row).find('empName').text();
$scope.Age = $(row).find('empAge').text();
$scope.City = $(row).find('empCity').text();
});
});
};

Resources