Ajax function not calling - angularjs

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

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().

Using $http with google suggestions - Convert from angularjs version 1.3.15 to version 1.6.4

First of all, I don't know much about angularjs. I did manage to patch together a single file web page with angularjs. I am having trouble converting the $http call from version 1.3.15 to version 1.6.4 as shown in the following:
var url = 'http://suggestqueries.google.com/complete/search?callback=JSON_CALLBACK&client=firefox&hl=en&q=' + encodeURIComponent($scope.searchText);
$http.defaults.useXDomain = true;
$http({
url: url,
method: 'JSONP',
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, PUT',
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}).
success(function(data, status, headers, config) {
$scope.suggestions = data[1];
}).
error(function(data, status, headers, config) {
$scope.suggestions = ['error connecting'];
});
Not real sure how it should look.
Here is the whole file:
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js#1.3.15" data-semver="1.3.15" src="https://code.angularjs.org/1.3.15/angular.js"></script>
<style>
#appDiv
{
position: fixed;
top: 30%;
left: 80%;
transform: translate(-80%, 0%);
width:50%;
}
#entry
{
width: 100%
}
#searchInput
{
display: table-cell;
color: #808080;
width:100%;
font-size:150%;
}
.goButton
{
font-size:150%;
}
.list
{
list-style-type: none;
margin: 0;
padding: 0;
cursor: default;
border-style: solid;
border-width: 1px;
border-color: #DFDFDF;
}
.list:empty
{
border-style: none;
}
.listItem
{
color: #404040;
font-size:120%;
}
.listItem:hover
{
background: #DFDFDF;
}
</style>
</head>
<body>
<div id="appDiv" ng-app="googleSearch" ng-controller="googleCtrl">
<form method="get" action="http://www.google.com/search" autocomplete="off">
<table border="0" align="center" cellpadding="0">
<tr>
<td id="entry">
<input type="text" name="q" id="searchInput" autofocus="autofocus" maxlength="255" ng-model="searchText" ng-keyup="search()" />
</td>
<td>
<input class="goButton" type="submit" value=" Go! "/>
<input type="hidden" name="sitesearch" value="" />
</td>
</tr>
<tr>
<td colspan="2" ng-mouseleave="restore()">
<ul class="list"><li class="listItem" ng-repeat="x in suggestions" ng-click="select(x)" ng-mouseover="preview(x)">{{x}}</li></ul>
</td>
</tr>
</table>
</form>
</div>
<script>
var app = angular.module("googleSearch", []);
app.controller("googleCtrl", function($scope, $http)
{
$scope.select = function(text)
{
$scope.searchText = text;
$scope.memory = text;
$scope.suggestions = [];
document.getElementById("searchInput").focus();
}
$scope.preview = function(text)
{
$scope.searchText = text;
}
$scope.restore = function()
{
$scope.searchText = $scope.memory;
}
$scope.search = function()
{
$scope.memory = $scope.searchText;
googleSearch();
}
googleSearch = function()
{
if ($scope.searchText == null || $scope.searchText.length < 1)
{
$scope.suggestions = [];
return
}
var url = 'http://suggestqueries.google.com/complete/search?callback=JSON_CALLBACK&client=firefox&hl=en&q=' + encodeURIComponent($scope.searchText);
$http.defaults.useXDomain = true;
$http({
url: url,
method: 'JSONP',
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, PUT',
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}).
success(function(data, status, headers, config) {
$scope.suggestions = data[1];
}).
error(function(data, status, headers, config) {
$scope.suggestions = ['error connecting'];
});
}
});
</script>
</body>
</html>
I am having trouble with the googleSearch function when I use:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
instead of:
<script data-require="angular.js#1.3.15" data-semver="1.3.15" src="https://code.angularjs.org/1.3.15/angular.js"></script>
in the head element. Any suggestions would be appreciated.
successand error are deprecated in $http api in favor of using promise callback
Also Access Control headers are for CORS and are only set on server as response headers not in request headers.
JSONP requests aaccept no headers since they are actually script requests no XMLHttpRequests.
you must now also declare JSONP url's as $sce trusted urls. Be sure to include angular-santize.js in page and inject $sce
Use then() and catch()
Try:
var url = 'http://suggestqueries.google.com/complete/search?client=firefox&hl=en&q=' + encodeURIComponent($scope.searchText);
var truestedUrl = $sce.trustAsResourceUrl(url);
$http.jsonp(truestedUrl , {jsonpCallbackParam: 'callback'}).then(function(response) {
$scope.suggestions = response.data[1];
}).catch(function(error) {
$scope.suggestions = ['error connecting'];
});
Reference $http.jsonp() docs
Final Google search file using angularjs 1.6.4
I just thought I would post my final result:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/angular-sanitize.js"></script>
<style>
#appDiv
{
position: fixed;
top: 30%;
left: 65%;
transform: translate(-65%, 0%);
width:50%;
}
#entry
{
width: 100%
}
#searchInput
{
display: table-cell;
color: #000000;
width:100%;
font-size:150%;
}
.goButton
{
font-size:150%;
}
input[type=submit]
{
padding:7px 0px 7px 0px;;
background: #00ff00;
border: 1px solid black;
border-radius: 5px;
}
.list
{
list-style-type: none;
margin: 0;
padding: 0;
cursor: default;
}
.listItem
{
color: #000000;
font-size:150%;
}
.listItem:hover
{
background: #DFDFDF;
}
</style>
</head>
<body>
<div id="appDiv" ng-app="googleSearch" ng-controller="googleCtrl">
<form method="get" action="http://www.google.com/search" autocomplete="off">
<table border="0" align="center" cellpadding="0">
<tr>
<td id="entry">
<input type="text" name="q" id="searchInput" autofocus="autofocus" maxlength="255" ng-model="searchText" ng-keyup="search()" />
</td>
<td>
<input class="goButton" type="submit" value=" Go! "/>
<input type="hidden" name="sitesearch" value="" />
</td>
</tr>
<tr>
<td colspan="2" ng-mouseleave="restore()">
<ul class="list"><li class="listItem" ng-repeat="x in suggestions" ng-click="select(x)" ng-mouseover="preview(x)">{{x}}</li></ul>
</td>
</tr>
</table>
</form>
</div>
<script>
var app = angular.module("googleSearch", []);
app.controller("googleCtrl", ['$scope', '$http', '$sce', function($scope, $http, $sce)
{
$scope.select = function(text)
{
$scope.searchText = text;
$scope.memory = text;
$scope.suggestions = [];
document.getElementById("searchInput").focus();
googleSearch();
}
$scope.preview = function(text)
{
$scope.searchText = text;
}
$scope.restore = function()
{
$scope.searchText = $scope.memory;
}
$scope.search = function()
{
$scope.memory = $scope.searchText;
googleSearch();
}
googleSearch = function()
{
if ($scope.searchText == null || $scope.searchText.length < 1)
{
$scope.suggestions = [];
return
}
var url = 'http://suggestqueries.google.com/complete/search?client=firefox&hl=en&q=' + encodeURIComponent($scope.searchText);
var truestedUrl = $sce.trustAsResourceUrl(url);
$http.jsonp(truestedUrl , {jsonpCallbackParam: 'callback'}).then(function(response) {
$scope.suggestions = response.data[1];
}).catch(function(error) {
$scope.suggestions = [];
});
}
}]);
</script>
</body>
</html>

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.

Displaying data using Bootstrap modal/angularjs from asp.net webapi

I'm new to bootstrap. I want to do CRUD operations on the employee data from asp.net WebAPI using Bootstrap-Modal. I'm able to display the data from webapi to angularJS using a table(ng-repeat). In every row, at the end, I've three buttons VIEW, DELETE and EDIT and another outside the table ADD.
I want, whenever a user clicks on the ADD, VIEW, DELETE and EDIT button, a bootstrap modal should pop up and we should be able to perform CRUD operations.
I've tried many instances but no luck on how to get the data on Modal. Please help.
The code is as follows:
WEBAPI:
public class EmployeeService
{
SampleDatabaseEntities sampleDBEntities = new SampleDatabaseEntities();
//ADD USER
public int saveEmployee(EmployeeTable employeeTable)
{
sampleDBEntities.EmployeeTables.Add(employeeTable);
sampleDBEntities.SaveChanges();
return employeeTable.E_ID;
}
public EmployeeTable getEmployeeById(int id)
{
return sampleDBEntities.EmployeeTables.Find(id);
}
public List<EmployeeTable> getEmployees()
{
return sampleDBEntities.EmployeeTables.ToList();
}
public void updateEmployee(int x, EmployeeTable employeeTable)
{
if (employeeTable.E_ID == x)
{
sampleDBEntities.Entry(employeeTable).State = EntityState.Modified;
sampleDBEntities.SaveChanges();
}
}
public void deleteEmployee(int id)
{
var employee = sampleDBEntities.EmployeeTables.Find(id);
if(employee !=null)
{
sampleDBEntities.Entry(employee).State = EntityState.Deleted;
sampleDBEntities.SaveChanges();
}
}
Angular Service:
angular.module('mainApp', []).
factory('employeeService', function ($http) {
var baseAddress = 'http://localhost:53254/api/employee/';
//var baseAddress = 'http://localhost:49595/MobileService/api/UserService/';
var url = "";
return {
getEmployeesList: function () {
url = baseAddress;
return $http.get(url);
},
getUser: function (employee) {
url = baseAddress + "Get/" + employee.E_id;
return $http.get(url);
},
addUser: function (employee) {
url = baseAddress + "post";
return $http.post(url, employee);
},
deleteUser: function (employee) {
url = baseAddress + "Delete/" + employee.E_Id;
return $http.delete(url);
},
updateUser: function (employee) {
url = baseAddress + "put/" + employee.E_Id;
return $http.put(url, employee);
}
};
});
Angular Controller:
angular.module('mainApp')
.controller('getEmployeeCrl', ['$scope', 'employeeService', function ($scope, employeeService) {
employeeService.getEmployeesList().then(function (response) {
$scope.employees = response.data;
}, function (err) {
$scope.errMessage = "Something wrong with server. Please try again.";
})
}]);
HTML:
<!DOCTYPE html>
<html ng-app="mainApp">
<head>
<title></title>
<meta charset="utf-8" />
<script src="../Scripts/angular.js"></script>
<script src="../mainApp.js"></script>
<script src="../Utilities/ConstantsFactory.js"></script>
<script src="../Services/EmployeeService.js"></script>
<script src="../Controllers/EmployeeController.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body ng-controller="getEmployeeCrl">
<div>
<h2 style="text-align:center; color:darkblue">PROJECT 51</h2>
</div>
<div class="container">
<div style="background-color:dimgray;color:white;padding:20px;">
<input type="button" value="Go to Employees" class="btn btn-info" />
<input type="button" value="Go to Clients" class="btn btn-info" style="width:145px" />
<button class="glyphicon glyphicon-plus btn btn-primary" value="Add" data-toggle="tooltip" data-placement="top" title="Add Data" style="float:right; width:50px"></button>
</div>
<br />
<table class="table table-bordered table table-condensed" ng-hide="!employees">
<thead style="background-color:palevioletred">
<tr style="text-decoration:solid;color:darkblue;">
<th>Id</th>
<th>Name</th>
<th>Job</th>
<th>Hire Date</th>
<th>Manager</th>
<th>Salary</th>
<th>Commission</th>
<th colspan="2">Edit/Delete</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="emp in employees ">
<td>{{emp.E_ID}}</td>
<td>{{emp.E_NAME}}</td>
<td>{{emp.E_JOB}}</td>
<td>{{emp.HIRE_DATE}}</td>
<td>{{emp.MANAGER_ID}}</td>
<td>{{emp.SALARY}}</td>
<td>{{emp.COMMISSION}}</td>
<td colspan="2" style="width:170px">
<input type="button" ng-model="emp.E_Id" value="View" class="btn btn-primary" style="width:70px" />
<input type="button" value="Edit" class="btn btn-primary" style="width:70px" />
<input type="button" value="Delete" class="btn btn-primary" style="width:70px" />
</td>
</tr>
</tbody>
</table>
<p class="alert alert-danger" ng-show="!employees">{{errMessage}} <span class="glyphicon glyphicon-refresh" ng-show="!employees"></span></p>
</div>
</body>
</html>
How can I make use of Bootstrap Modal for CRUD operations

Custom directive breaking code in AngularJS

I need to add a custom directive to my code, but every time I add it, it breaks my code. I checked the console and is giving me the following error
Error: Argument 'guessGameController' is not a function, got undefined
at Error (native)
Now I am not sure if I am not setting my code right or if I am not adding the directive where is supposed to go. Here is my code, I appreciate all the help.
index.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" ng-app="guessGameApp">
<head>
<title>Word Game 2.0 - AngularJS</title>
<!--Encoding-->
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<!-- JQuery -->
<script src="js/jquery-1.11.0.min.js"></script>
<!--Scripts-->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js" type="text/javascript"></script>
<script src="js/controllers/app.js" type="text/javascript"></script>
<script src="js/controllers/maincontroller.js" type="text/javascript"></script>
<!--Styles-->
<link rel="stylesheet" type="text/css" href="css/magicWord.css">
<!--<script src="js/jquery-1.11.0.min.js"></script>-->
</head>
<body>
<div ng-controller="guessGameController">
<p>
<header id="masthead">
<h2 align="center">{{appTitle}}</h2>
</header>
</p>
<div ng-controller="wordController">
<p>
<table align="center" width="300px" height="150px" border="solid 2px">
<tr>
<td id="guessBox">
<p align="center">
<input value="" type="text" id="guestGuess" placeholder="Enter Guess" ng-model="guestGuess"/>
</p>
<p align="center"><button ng-click="addGuess()" id="guessButton">Click to Check</button></p>
</td>
</tr>
<tr>
<td>
<h3 align="center">Your guesses so far are: </h3>
<p align="center" ng-repeat="words in guesses">{{words}}</p>
</td>
</tr>
<tr>
<td>
<p align="center">You have guessed:<b>{{guessed}}</b> times out {{allowed}} chances.</p>
<p align="center">You have <b>{{allowed - guessed}}</b> guesses left.</p>
</td>
</tr>
<tr>
<td>
<a custom-button>Click me</a>
<br />
<button custom-button>Hello</button>
</td>
</tr>
</table>
</p>
</div>
</div>
</body>
</html>
app.js
var gameApp = angular.module('guessGameApp', []);
var gameTemplate = angular.module('guessGameApp', []);
maincontroller.js
gameApp.controller("guessGameController", function($scope)
{
$scope.appTitle = "WELCOME TO THE GUESS GAME!";
});
gameApp.controller('wordController', function($scope)
{
$scope.guess = '';
$scope.guesses = [];
$scope.guessed= '';
$scope.allowed = 6;
$scope.wordToGuess = "Just";
$scope.pushGuess = function () {
$scope.guesses.push($scope.guestGuess);
$scope.guessed = $scope.guesses.length;
$scope.resetGuess();
}
$scope.resetGuess = function() {
$scope.guestGuess = '';
}
$scope.addGuess = function()
{
if ($scope.guestGuess == null || $scope.guestGuess == '')
{
$("input[type=text]").ready(function () { $("#guestGuess").addClass("blur"); });
$scope.result = " Please enter a guess\n\nDon't leave the box empty.";
alert($scope.result);
}
else if ($scope.guestGuess.toLowerCase() == $scope.wordToGuess.toLowerCase())
{
$("input[type=text]").ready(function () { $("#guestGuess").removeClass("blur"); });
$scope.pushGuess(guestGuess);
$scope.result = "You have guessed the correct word. Way to go!\n\n\t\t The word was: ";
alert($scope.result + $scope.wordToGuess);
}
else if ($scope.guestGuess != $scope.wordToGuess & ($scope.allowed - $scope.guessed) > 1)
{
$("input[type=text]").ready(function () { $("#guestGuess").removeClass("blur"); });
$scope.pushGuess(guestGuess);
$scope.result = "Please try again!";
alert($scope.result);
}
else if (($scope.allowed - $scope.guessed) <= 1)
{
$("input[type=text]").ready(function () { $("#guestGuess").addClass("doneBlur"); });
$scope.guesses.push($scope.guestGuess);
$scope.guessed = $scope.guesses.length;
$scope.result = "Game over! The word was: ";
alert($scope.result + $scope.wordToGuess);
}
$scope.guess = '';
}
});
gameApp.directive('customButton', function ()
{
$scope.wordToGuess = "Just";
return {
restrict: 'A',
replace: true,
transclude: true,
templateUrl: '../../templates/customTemplate.HTML',
link: function (scope, element, attrs)
{
element.bind("click",function()
{
alert("The value of 'guessWord' is " + scope.wordToGuess);
})
}};
});
customTemplate.html
<a href="" class="myawesomebutton" ng-transclude>
<i class="icon-ok-sign"></i>
</a>
In app.js remove the second module declaration
var gameApp = angular.module('guessGameApp', []);
//var gameTemplate = angular.module('guessGameApp', []); --> remove this line
You are also modifying DOM from the controller, this is not the angular way. If you want to add classes when some condition occurs, then have a look at ng-class

Resources