Inter-Service Communication Causes Front-End Error - backbone.js

When logging in, an AJAX request is made through the service Account.Login.Service.ss. In this service I am also calling my own service WebStore.Service.ss - this is the inter-service communication I refer to.
Weirdly this inter-service communication works backend, but the front-end complains with the following error:
Uncaught SyntaxError: Unexpected token < in JSON at position 0
Screenshot of error:
The response from the original AJAX/XHR request is HTML (which is why the above error is complaining about the <). See the below snippet for the response from the XHR/AJAX request. If I remove the inter-service communication then everything works fine.
My service WebStore.Service.ss responds with JSON not HTML so I don't think its the cause.
Any idea what is wrong and how I can get inter-service communication to work?
Details:
Below specifically details the services code:
Account.Login.Service.ss
// Account.Login.Service.ss
function service (request)
{
'use strict';
var Application = require('Application');
try
{
var method = request.getMethod()
, Account = require('Account.Model')
, data = JSON.parse(request.getBody() || '{}');
// Call service
// Note no error occurs and everything works.
try {
var headers = {"User-Agent-x": "SuiteScript-Call",
"Content-Type": "application/json"};
var response = nlapiRequestURL("http://mywebsite.com/sca-dev-montblanc/services/WebStore.Service.ss?type=is_email_valid&email=foo%40bar.com", null, headers);
console.log("Making Service call", response);
}
catch (ex) {
console.log("Error:", e.message); // no error occurs
}
// END DEBUG
switch (method)
{
case 'POST':
//Handles the login and send the response
Application.sendContent(Account.login(data.email, data.password, data.redirect));
break;
default:
// methodNotAllowedError is defined in ssp library commons.js
Application.sendError(methodNotAllowedError);
}
}
catch (e)
{
Application.sendError(e);
}
}
WebStore.Service.ss
function service(request, response)
{
var Application = require('Application');
try {
if (request.getMethod() == 'GET') {
Application.sendContent( {foo: "bar"} );
}
}
catch (e) {
Application.sendError(e);
}
}
Response from http://.../Account.Login.Service.ss?n=2&c=4224945&n=2
<!DOCTYPE html>
<html>
<head>
<title>Notice (SuiteScript)</title>
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
<script type='text/javascript' src='/ui/jquery/jquery-1.11.3.min.js?NS_VER=2017.1.0&minver=75'></script>
<script type='text/javascript' src='/ui/jquery/jquery_isolation.js?NS_VER=2017.1.0&minver=75'></script>
<script type='text/javascript' src='/javascript/NLUtil.jsp?NS_VER=2017.1.0&minver=75&locale=en_AU&JSP_VER=1&locale=en_AU&JSP_VER=1&JSP_VER=1'></script>
<script type='text/javascript' src='/javascript/NLUtil.js?NS_VER=2017.1.0&minver=75'></script>
<script type='text/javascript' src='/javascript/NLUIWidgets.jsp?NS_VER=2017.1.0&minver=75&locale=en_AU&JSP_VER=1&locale=en_AU&JSP_VER=1&JSP_VER=1'></script>
<script type='text/javascript' src='/assets/legacy_widgets/1701411811.js?NS_VER=2017.1.0&minver=75'></script>
<script type='text/javascript' src='/assets/legacy_apputil/1733410633.js?NS_VER=2017.1.0&minver=75'></script>
<script type='text/javascript' src='/javascript/NLAppUtil.jsp?NS_VER=2017.1.0&minver=75&locale=en_AU&JSP_VER=1&locale=en_AU&JSP_VER=1&JSP_VER=1'></script>
<script type='text/javascript' src='/uirefresh/script/global.js__NS_VER=2017.1.0&minver=75&locale=en_AU.nlqs?NS_VER=2017.1.0&minver=75'></script>
<link rel='stylesheet' href='/core/styles/pagestyles.nl'><link rel='stylesheet' type='text/css' href='/uirefresh/css/button.css' />
</head>
<body bgcolor='#FFFFFF' link='#000000' vlink='#000000' alink='#330099' text='#000000' topmargin='0' marginheight='1' onload='page_init()' class='error-page'>
<img src='/images/nav/stretch.gif' width='10'><img class='uir-logo' src='/images/logos/netsuite-reskin.png' border=0 style='margin-right:30px;'><img src='/images/logos/sandbox_logo.gif' height='30' width='125' border=0>
<table border=0 cellPadding=0 cellSpacing=0 width=100%>
<tr><td class='bglt'>
<table border='0' cellspacing='0' cellpadding='5' width='100%'>
<tr><td class='textboldnolink'>Notice (SuiteScript)</td></tr>
<tr><td vAlign='top'>
<table border='0' cellspacing='0' cellpadding='0' width='100%'>
<tr><td class='text'> </td></tr>
<tr><td class=text><img src='/images/5square.gif' width=5 height=5>An unexpected SuiteScript error has occurred</td></tr>
<tr><td class='text'> </td></tr>
<tr><td class='text'> </td></tr>
</table></td></tr></table></td></tr>
<tr><td> <table id='tbl_goback' cellpadding='0' cellspacing='0' border='0' class='uir-button' style='margin-right:6px;cursor:hand;' role='presentation'> <tr id='tr_goback' class='pgBntG pgBntB'> <td id='tdleftcap_goback'><img src='/images/nav/ns_x.gif' class='bntLT' border='0' height='50%' width='3' alt=''/> <img src='/images/nav/ns_x.gif' class='bntLB' border='0' height='50%' width='3' alt=''/> </td> <td id='tdbody_goback' height='20' valign='top' nowrap class='bntBgB'> <input type='button' style='' class='rndbuttoninpt bntBgT' value='Go Back' id='goback' name='goback' onclick="history.back(); return false;" onmousedown="this.setAttribute('_mousedown','T'); setButtonDown(true, false, this);" onmouseup="this.setAttribute('_mousedown','F'); setButtonDown(false, false, this);" onmouseout="if(this.getAttribute('_mousedown')=='T') setButtonDown(false, false, this);" onmouseover="if(this.getAttribute('_mousedown')=='T') setButtonDown(true, false, this);" ></td> <td id='tdrightcap_goback'> <img src='/images/nav/ns_x.gif' height='50%' class='bntRT' border='0' width='3' alt=''> <img src='/images/nav/ns_x.gif' height='50%' class='bntRB' border='0' width='3' alt=''> </td> </tr> </table> </td></tr>
</table>
<script language='JavaScript' type='text/javascript'>
function page_init() {
}
</script>
</body>
</html>

Your Account.Login.Service.ss is only responding with html because there is an error that NetSuite is trying to tell you about. Usually it would send JSON too. You comment inside the code that // no error occurs following a console.log() call, but this could be what's causing the problem. You are trying to log to the console from a server side service, so that won't work. Use nlapiLogExecution() instead.

Related

Display all childs in Firebase Database (Web)

So I successfully displaying 1 database from my firebase using limitToLast function. Here is the webpage look like
Kinda curious how to display all of my databases (all childs from selected parent) from firebase console using javascript?
List of my database in firebase that I want to display
and here is my code below:
firebase.initializeApp(config);
var order = firebase.database().ref("order");
order.on("value", function(snapshot) {
console.log(snapshot.val());
}, function (error) {
console.log("Error: " + error.code);
});
var submitOrder = function () {
var orderId = $("#orderOrderId").val();
var shipping = $("#orderShipping").val();
var subtotal = $("#orderSubtotal").val();
var total = $("#orderTotal").val();
};
order.limitToLast(1).on('child_added', function(childSnapshot) {
order = childSnapshot.val();
$("#orderId").html(order.orderId)
$("#shipping").html(order.shipping)
$("#subtotal").html(order.subtotal)
$("#total").html(order.total)
$("#link").attr("https://wishywashy-179b9.firebaseio.com/", order.link)
});
<html>
<head>
<script src="https://www.gstatic.com/firebasejs/5.3.0/firebase.js"></script>
<script src="https://cdn.firebase.com/libs/firebaseui/2.5.1/firebaseui.js"></script>
<link type="text/css" rel="stylesheet" href="https://cdn.firebase.com/libs/firebaseui/2.5.1/firebaseui.css" />
<!-- <script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script> -->
<!-- Load the jQuery library, which we'll use to manipulate HTML elements with Javascript. -->
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<!-- Load Bootstrap stylesheet, which will is CSS that makes everything prettier and also responsive (aka will work on all devices of all sizes). -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>
<!-- <script type = "text/javascript" src = "data.js"></script> -->
<body>
<script type = "text/javascript" src = "data.js"></script>
<div class="container">
<h1>Merchant Portal</h1>
<h3>Order Lists</h3>
<table class="table table-striped">
<thead>
<tr>
<th>Order ID</th>
<th>Shipping Price</th>
<th>Subtotal</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<!-- This is empty for now, but it will be filled out by an event handler in application.js with the most recent recommendation data from Firebase. -->
<td id="orderId"></td>
<td id="shipping"></td>
<td id="subtotal"></td>
<td id="total"></td>
</tr>
</tbody>
</table>
</body>
</html>
You will need to generate a new <tr> for each order. A very simple way to do this is simply generate the DOM elements in your on('child_added' callback:
var table = document.querySelector("tbody");
order.on('child_added', function(childSnapshot) {
order = childSnapshot.val();
var tr = document.createElement('tr');
tr.appendChild(createCell(order.orderId));
tr.appendChild(createCell(order.shipping));
tr.appendChild(createCell(order.subTotal));
tr.appendChild(createCell(order.total));
table.appendChild(tr);
});
As you can see, this code creates a new <tr> for each child/order, and populates that with simple DOM methods. It then adds the new <tr> to the table.
This code uses a simple helper function to handle the repetitious creating of <td> elements with a text node in them:
function createCell(text) {
var td = document.createElement('td');
td.appendChild(document.createTextNode(text));
return td;
}

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.

AngularJS ng-click not firing controller method

I'm sure everyone has seen questions of a similar ilk, and trust me when I say I have read all of them in trying to find an answer. But alas without success. So here goes.
With the below code, why can I not get an alert?
I have an ASP.Net MVC4 Web API application with AngularJS thrown in. I have pared down the code as much as I can.
I know that my AngularJS setup is working correctly because on loading my view it correctly gets (via a Web API call) and displays data from the database into a table (the GetAllRisks function). Given that the Edit button is within the controller, I shouldn't have any scope issues.
NB: the dir-paginate directive and controls are taken from Michael Bromley's excellent post here.
I would appreciate any thoughts as my day has degenerated into banging my head against my desk.
Thanks,
Ash
module.js
var app = angular.module("OpenBoxExtraModule", ["angularUtils.directives.dirPagination"]);
service.js
app.service('OpenBoxExtraService', function ($http) {
//Get All Risks
this.getAllRisks = function () {
return $http.get("/api/RiskApi");
}});
controller.js
app.controller("RiskController", function ($scope, OpenBoxExtraService) {
//On load
GetAllRisks();
function GetAllRisks() {
var promiseGet = OpenBoxExtraService.getAllRisks();
promiseGet.then(function (pl) { $scope.Risks = pl.data },
function (errorPl) {
$log.error("Some error in getting risks.", errorPl);
});
}
$scope.ash = function () {
alert("Bananarama!");}
});
Index.cshtml
#{
Layout = null;
}
<!DOCTYPE html>
<html ng-app="OpenBoxExtraModule">
<head>
<title>Risks</title>
<link href="~/Content/bootstrap.min.css" rel="stylesheet">
<script type="text/javascript" src="~/Scripts/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="~/Scripts/bootstrap.min.js"></script>
<script type="text/javascript" src="~/Scripts/angular.js"></script>
<script type="text/javascript" src="~/Scripts/AngularJS/Pagination/dirPagination.js"></script>
<script type="text/javascript" src="~/Scripts/AngularJS/module.js"></script>
<script type="text/javascript" src="~/Scripts/AngularJS/service.js"></script>
<script type="text/javascript" src="~/Scripts/AngularJS/controller.js"></script>
</head>
<body>
<div ng-controller="RiskController">
<table>
<thead>
<tr>
<th>Risk ID</th>
<th>i3_n_omr</th>
<th>i3_n_2_uwdata_key</th>
<th>Risk Reference</th>
<th>Pure Facultative</th>
<th>Timestamp</th>
<th></th>
</tr>
</thead>
<tbody>
<tr dir-paginate="risk in Risks | itemsPerPage: 15">
<td><span>{{risk.RiskID}}</span></td>
<td><span>{{risk.i3_n_omr}}</span></td>
<td><span>{{risk.i3_n_2_uwdata_key}}</span></td>
<td><span>{{risk.RiskReference}}</span></td>
<td><span>{{risk.PureFacultative}}</span></td>
<td><span>{{risk.TimestampColumn}}</span></td>
<td><input type="button" id="Edit" value="Edit" ng-click="ash()"/></td>
</tr>
</tbody>
</table>
<div>
<div>
<dir-pagination-controls boundary-links="true" template-url="~/Scripts/AngularJS/Pagination/dirPagination.tpl.html"></dir-pagination-controls>
</div>
</div>
</div>
</body>
</html>
you cannot use ng-click attribute on input with angularjs : https://docs.angularjs.org/api/ng/directive/input.
use onFocus javascript event
<input type="text" onfocus="myFunction()">
or try to surround your input with div or span and add ng-click on it.
I've got the working demo of your app, code (one-pager) is enclosed below, but here is the outline:
removed everything concerning dirPagination directive, replaced by ngRepeat
removed $log and replaced by console.log
since I don't have a Web API endpoint, I just populated $scope.Risks with some items on a rejected promise
Try adjusting your solution to first two items (of course, you won't populate it with demo data on rejected promise)
<!doctype html>
<html lang="en" ng-app="OpenBoxExtraModule">
<head>
<meta charset="utf-8">
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
var app = angular.module("OpenBoxExtraModule", []);
app.service('OpenBoxExtraService', function ($http) {
//Get All Risks
this.getAllRisks = function () {
return $http.get("/api/RiskApi");
}
});
app.controller("RiskController", function ($scope, OpenBoxExtraService) {
//On load
GetAllRisks();
function GetAllRisks() {
var promiseGet = OpenBoxExtraService.getAllRisks();
promiseGet.then(function (pl) { $scope.Risks = pl.data },
function (errorPl) {
console.log("Some error in getting risks.", errorPl);
$scope.Risks = [{RiskID: "1", i3_n_omr: "a", i3_n_2_uwdata_key: "b", RiskReference: "c", PureFacultative:"d", TimestampColumn: "e"}, {RiskID: "2", i3_n_omr: "a", i3_n_2_uwdata_key: "b", RiskReference: "c", PureFacultative:"d", TimestampColumn: "e"}, {RiskID: "3", i3_n_omr: "a", i3_n_2_uwdata_key: "b", RiskReference: "c", PureFacultative:"d", TimestampColumn: "e"} ];
});
}
$scope.ash = function () {
alert("Bananarama!");}
});
</script>
</head>
<body>
<div ng-controller="RiskController">
<table>
<thead>
<tr>
<th>Risk ID</th>
<th>i3_n_omr</th>
<th>i3_n_2_uwdata_key</th>
<th>Risk Reference</th>
<th>Pure Facultative</th>
<th>Timestamp</th>
<th></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="risk in Risks">
<td><span>{{risk.RiskID}}</span></td>
<td><span>{{risk.i3_n_omr}}</span></td>
<td><span>{{risk.i3_n_2_uwdata_key}}</span></td>
<td><span>{{risk.RiskReference}}</span></td>
<td><span>{{risk.PureFacultative}}</span></td>
<td><span>{{risk.TimestampColumn}}</span></td>
<td><input type="button" id="Edit" value="Edit" ng-click="ash()"/></td>
</tr>
</tbody>
</table>
<div>
<div></div>
</div>
</div>
</body>
</html>
Thank you all for your help, particularly #FrailWords and #Dalibar. Unbelievably, this was an issue of caching old versions of the javascript files. Doh!
You can't directly use then on your service without resolving a promise inside it.
fiddle with fallback data
this.getAllRisks = function () {
var d = $q.defer();
$http.get('/api/RiskApi').then(function (data) {
d.resolve(data);
}, function (err) {
d.reject('no_data');
});
return d.promise;
}
This will also fix your problem with getting alert to work.

angular $injector:unpr Error

Im trying to use Resource in my app and I get the following error:
$injector:unpr
"errors.angularjs.org/1.3.15/$injector/unpr?p0=mkResourceProvider%20%3C-%20mkResource%20%3C-%20mkController".
Here is my Code
app
var logApp = angular.module('mkApp', ['ngResource','ngRoute']);
Controller
angular.module('mkApp').controller('mkController', function ($scope, mkResource) {
$scope.ddl = [];
mkResource.LookUp(function (data) {
$scope.ddl = data;
console.log($scope.ddl);
});});
Resource
angular.module('mkApp').factory('mkResource', function ($resource, $http) {
var lookup = $resource('api/HowOftens');
function LookUp() {
return lookup.query();
}
return {
LookUp: LookUp
}});
HTML
<head>
<script src="../Scripts/angular.min.js"></script>
<script src="../Scripts/jquery-2.1.3.min.js"></script>
<title></title>
<div ng-app="mkApp">
<div ng-controller="mkController">
<table>
<tr>
<td> F Name</td>
<td> L Name</td>
</tr>
<tr>
<td><input type="text" /></td>
<td><input type="text" /></td>
</tr>
<tr>
<td>
<slect></slect>
</td>
</tr>
</table>
</div>
</div>
<script src="MkApp/MkApp.js"></script>
<script src="Controller/MkController.js"></script>
<script src="../Scripts/angular-resource.min.js"></script>
<script src="../Scripts/angular-route.min.js"></script>
From all the reading ive been doing i understand its injection error. I don't understand what Im not injecting properly though. The final plan was to load ddls from data I will receive.
You would need to be loading your angular-route and angular-resource (your libs) before you actually load up your angular app files.

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