I have an angular app, and an index.html with an ng-view that renders to different views partials/persons.html and partials/newPerson.html.
when i add a new person to the $scope.persons in my controller via the newPerson.html the $scope.persons is updated, but it dosn´t updated the table in the partials/persons.html. if i copy/paste the table into partials/newPerson.html the table is updated automatically. I cant seem to wrap my head around why? they are using the same controller...?
thank´s in advance for your help :)
js/app.js
var app = angular.module('app',['ngRoute']);
app.config(function($routeProvider){
$routeProvider
.when('/persons',{
templateUrl:'partials/persons.html',
controller:'PersonCtrl'
})
.when('/newperson',{
templateUrl:'partials/newPerson.html',
controller:'PersonCtrl'
})
.otherwise({
redirectTo: '/'
});
});
app.controller('PersonCtrl',['$scope', function($scope){
var persons = [
{
id: 1
,name: "Jens",
age : 18}
,{
id: 2,
name: "Peter",
age : 23
}
,{
id: 3
,name: "Hanne"
,age : 23
}
];
$scope.persons = persons;
$scope.nextId = 4;
$scope.savePerson = function(){
if($scope.newPerson.id === undefined)
{
$scope.newPerson.id= $scope.nextId++;
$scope.persons.push($scope.newPerson);
}else{
for (var i = 0; i < $scope.persons.length; i++) {
if($scope.persons[i].id === $scope.newPerson.id){
$scope.persons[i] = $scope.newPerson;
break;
}
}
}
$scope.newPerson = {};
};
index.html
<html ng-app="app" ng-controller="PersonCtrl">
<head>
<title>Routing</title>
<link rel="stylesheet" href="css/styles.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.js"></script>
<script src="https://code.angularjs.org/1.4.7/i18n/angular-locale_da.js"></script>
<script src="angularSrc/app.js"></script>
</head>
<body>
<br>
<div class="container">
<header>
<h1>People Routing</h1>
<nav>
persons
new person
</nav>
</header>
<div ng-view="ng-view">
</div>
</div>
</body>
partials/persons.html
<h3>Persons</h3>
<table >
<thead>
<tr>
<td>Id</td>
<td>name</td>
<td>age</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="p in persons">
<td>{{p.id}} </td>
<td>{{p.name}} </td>
<td>{{p.age}} </td>
</tr>
</tbody>
</table>
partials/newPerson.html
<div >
<h1>New person</h1>
<form class="form-horizontal">
<fieldset>
<div class="form-group">
<input type="text" ng-model="newPerson.name" model="newPerson.name" class="form-control" id="year" placeholder="name">
</div>
<div class="form-group">
<input type="number" ng-model="newPerson.age" model="newPerson.age" class="form-control" id="age" placeholder="age">
</div>
</fieldset>
</form>
<button type="submit" ng-click="savePerson()" >Save</button>
<h2>nextId: {{nextId}}</h2>
</div>
The problem is that you aren't realizing that each use of controller creates new instance.
The scope is destroyed when you leave a controller so if you add to the scope in one instance , that change will be lost when you load controller again on your other route.
You need to use a service to persist the data during the life of each page load.
Simple service example:
app.factory('PersonService', function () {
var persons = [{
id: 1,
name: "Jens",
age: 18
}, {
...
}, {
...
}];
return {
persons: persons
}
});
Then inject in controller and use the service data in controller
app.controller('PersonCtrl',['$scope','PersonService', function($scope,PersonService){
$scope.persons = PersonService.persons;
Related
I want to update my view(an input form) to add products to database. For a single product I am able to add it by making it into an array, but now I want to add multiple products and with the click of a button "Add more Product", a similar view(form) is to be generated below the existing form, and this can go on multiple times(to be determined at run time). Now I have two problems:
1. How to update my view with every (Add more Product)button click. Is it done by maintaining some count?
2. How to add multiple product values from each of the forms into the the array of object.
$scope.onClick = function () {
$scope.productData =
{
name: $scope.name,
description: $scope.description,
price: $scope.price,
image: $scope.image,
tags: $scope.tags,
partner_id: $scope.partner_id,
};
}
Example Code
There are a ton of ways to do this. I made this sample plunker that shows a simple option of toggling a form div, adding data in the form, then pushing the resulting form object to the primary products array.
EDIT: I refactored my plunk and snippet to use a Javascript class and constructor. Cloning a master object as shown below is another way to perform this task.
https://embed.plnkr.co/IsNifSaF8jE7oOog29dK/
(See the full snippet at the bottom of this answer.)
Explanation
In your code, you are using $scope on all of your object properties. What you should actually do is create one top-level scope array that is the result of your products retrieval from the server. I would actually create a JavaScript constructor / class that matches the product object you need in the database (for brevity, I just created a "master" object and a cloned "newProduct" object to make edits to):
// Sample Product Object
$scope.newProduct= {
name: "",
description: "",
price: 0.00,
image: "",
tags: [],
partner_id: 0
};
You can bind your $scope.newProduct object to the form with ng-model.
<!-- ==== Simplified Form ==== -->
<form class="form" ng-submit="submitNewProduct()">
<div class="form-group">
<label>Product Name: </label>
<input class="form-control" type="text" ng-model="newProduct.name" >
</div>
<input type="submit" class="btn btn-info" />
</form>
Now when you submit the new product data, you can manipulate it however you need to in the controller (via the $scope.submitNewProduct() function). Once the object is successfully inserted into your database and you're done manipulating the data, you can push the finalized "new product" object into the products array. AngularJs will update the view for you (bound objects via ng-model are being watched for changes) once you add the new product to the array:
// If server update is successful, add new product to products array
$scope.products.push($scope.newProduct);
If you aren't using a constructor, just make sure to note that I reset the $scope.newProduct object back to default values so it doesn't carry over any new changes when you open the new product form again.
// Reset placeholder product
$scope.newProduct = $scope.masterProduct;
Helpful Resources
Tutorial Vids: https://youtu.be/MzqkIZLkBsU
Javascript Constructors: https://www.w3schools.com/js/js_object_constructors.asp
ngRepeat Examples: https://www.w3schools.com/angular/ng_ng-repeat.asp
Snippet
(function() {
"use strict";
var app = angular.module("myApp", []);
app.controller("myController", myController);
myController.$inject = ["$scope", "$timeout", "$filter"];
function myController($scope, $timeout, $filter) {
$scope.loading = false;
class Product {
constructor(_name, _description, _price) {
this.id = this.getNewId();
this.name = _name;
this.description = _description;
this.price = _price;
this.image = "https://www.thesweetexplosion.co.uk/wp-content/uploads/2013/06/product-placeholder.jpg";
this.tags = [];
this.partner_id = 0;
}
getNewId() {
var latestId = $scope.products[$scope.products.length - 1].id
return latestId + 1;
}
}
// Pretending we received these products received from the database...
$scope.products = [{
id: 0,
name: "product_1",
description: "product_1 description",
price: 52.23,
image: "https://raspberrypi.dk/wp-content/uploads/2014/07/raspberry-pi-model-b-plus1.png",
tags: [],
partner_id: 345214967
}, {
id: 1,
name: "product_2",
description: "product_2 description",
price: 46.23,
image: "https://modtronix.com.au/wp-content/uploads/enc-rpi3-official_bottom_ll-100x100.jpg",
tags: [],
partner_id: 514852924
}];
// Add new Products by using this base object
$scope.placeholderProduct = {
id: 0,
name: "",
description: "",
price: 0.00,
image: "https://www.thesweetexplosion.co.uk/wp-content/uploads/2013/06/product-placeholder.jpg",
tags: [],
partner_id: 0
};
$scope.createNewProduct = function(){
$scope.newProduct = new Product("", "", 0);
}
$scope.submitNewProduct = function() {
// DO SERVER UPDATING HERE
// Show loading
$scope.updating = true;
// Simulate server update
$timeout(function() {
// If server update is successful, add new product to products array
$scope.products.push($scope.newProduct);
// Reset submit button
$scope.updating = false;
// Reset placeholder product
$scope.newProduct = {};
// Hide products form
$scope.addProductForm = false;
}, 1000);
}
}
})();
.productImg {
width: 50px;
height: 50px;
}
.prodForm {
margin-top: 15px;
margin-bottom: 15px;
;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.1/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://use.fontawesome.com/releases/v5.0.9/js/all.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="myApp" ng-controller="myController">
<div class="container">
<div class="row">
<div class="col-xs-12">
<div class="jumbotron text-center">
<h3>AngularJS (1.3.1) - Instantiating Products with ES6 Class Constructor</h3>
</div>
</div>
</div>
<!-- New Product Form - Toggled with addProductForm -->
<div class="col-xs-12">
<button type="button" class="btn btn-sm btn-success" ng-click="createNewProduct(); addProductForm = !addProductForm" ng-show="!addProductForm">
<span class="glyphicon-plus"> Add New Product</span>
</button>
<button type="button" class="btn btn-sm btn-danger" ng-click="addProductForm = !addProductForm" ng-show="addProductForm">
<span>Clear</span>
</button>
</div>
<div class="col-xs-12 well prodForm" ng-show="addProductForm">
<form class="form" ng-submit="submitNewProduct()">
<div class="form-group">
<label>Product Name: </label>
<input class="form-control" type="text" ng-model="newProduct.name" >
</div>
<div class="form-group">
<label>Description: </label>
<input class="form-control" type="text" ng-model="newProduct.description" />
</div>
<div class="form-group">
<label>Price: </label>
<input class="form-control" type="number" min="0.01" step="0.01" ng-model="newProduct.price" format="currency" />
</div>
<div class="form-group">
<label>Partner Id: </label>
<input class="form-control" type="number" ng-model="newProduct.partner_id" />
</div>
<input type="submit" class="btn btn-info" ng-show="!updating" />
<button type="button" class="btn btn-info" ng-show="updating"><i class="fa fa-spinner fa-spin"></i> Updating...</button>
</form>
</div>
<!-- Primary Products Table -->
<div class="col-xs-12">
<table class="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Price</th>
<th>Image</th>
<th>Tags</th>
<th>Partner Id</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="product in products track by $index">
<td>{{ product.name }}</td>
<td>{{ product.description }}</td>
<td>{{ product.price | currency }}</td>
<td>
<img class="productImg" ng-src="{{ product.image }}" alt="{{ product.name }} img" />
</td>
<td>{{ product.tags }}</td>
<td>{{ product.partner_id }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>
I am working on a sample app using angularJS.
I have a service which returns JSON object, I am trying to bind the response to a table.
Controller -
(function () {
var app = angular.module('searchApp', []);
app.config(function ($sceDelegateProvider) {
$sceDelegateProvider.resourceUrlWhitelist(['http://localhost:11838/SearchProfiles/get']);
});
var controller = app.controller('searchController', ["$scope", "$http", function ($scope, $http) {
$scope.profileName = "";
$http.get("http://localhost:11838/SearchProfiles/GetAllRuleSets")
.then(function (response) {
$scope.ruleSets = response.data;
});
$scope.searchProfiles = function () {
$http.get("http://localhost:11838/SearchProfiles/GetProfiles?profileName=" + $scope.profileName
+ "&ruleSetName=" + $scope.selectedRuleSet)
.then(function (response) {
$scope.showProfiles = true;
$scope.profiles = response.data;
console.log($scope.profiles);
});
};
$scope.clearForm = function () {
$scope.profileName = "";
$scope.selectedRuleSet = "";
};
}]);
})();
cshtml -
#{
ViewBag.Title = "Search Profiles";
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Search Profiles</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
#Scripts.Render("~/Scripts/angular")
#Styles.Render("~/Content/css/scss")
</head>
<body ng-app="searchApp">
<div ng-controller="searchController" id="content">
<label>Profile Name: </label>
<input type="text" name="profileName" ng-model="profileName" /><br />
<label>RuleSet Name: </label>
<select ng-model="selectedRuleSet" ng-options="x for x in ruleSets"></select><br />
<button name="search" ng-click="searchProfiles()">Search</button>
<button name="clear" ng-click="clearForm()">Clear</button>
</div>
<div ng-controller="searchController" id="profilesDiv">
<table>
<tr ng-repeat="x in profiles">
<td>{{ x.ProfileName }}</td>
<td>{{ x.CreationDate }}</td>
</tr>
</table>
</div>
</body>
I am getting back following response -
[{"ProfileName":"Profile3","CreationDate":"1/9/2017"},{"ProfileName":"Profile4","CreationDate":"12/30/2016"}]
but even after setting $scope.profiles I am not seeing table on UI.
I'm fairly new to angular, am I missing something obvious.
Any help is appreciated.
The problem is that you are fetching the data in one scope (the div content where you declare ng-controller="searchController") and then trying to
view the data in another scope (the div profilesDiv where you again declare the ng-controller="searchController").
To solve the problem you need to remove ng-controller="searchController" from the profilesDiv and move the profilesDiv inside the content div.
Like this:
<body ng-app="searchApp">
<div ng-controller="searchController" id="content">
<label>Profile Name: </label>
<input type="text" name="profileName" ng-model="profileName" /><br />
<label>RuleSet Name: </label>
<select ng-model="selectedRuleSet" ng-options="x for x in ruleSets"></select><br />
<button name="search" ng-click="searchProfiles()">Search</button>
<button name="clear" ng-click="clearForm()">Clear</button>
<div id="profilesDiv">
<table>
<tr ng-repeat="x in profiles">
<td>{{ x.ProfileName }}</td>
<td>{{ x.CreationDate }}</td>
</tr>
</table>
</div>
</div>
</body
I have the following code :
http://plnkr.co/edit/RqLurBaCsgjQjOYMtl8r?p=preview
here there is a textbox and when user add something to the textbox and push add button then the entered text should be added to the table Here is my javaScript code:
var app = angular.module('app', []);
app.factory('Service', function() {
var typesHash = [ {
id : '1',
name : 'lemon',
price : 100,
unit : 2.5
}, {
id : '2',
name : 'meat',
price : 200,
unit : 3.3
} ];
var service = {
addTable : addTable,
getData : getData,
};
return service;
function addTable(data) {
typesHash.push(data);
}
function getData() {
return typesHash;
}
});
app.controller('table', function(Service) {
//get the return data from getData funtion in factory
this.typesHash = Service.getData();
this.testData = {
id : '1',
name : "test",
price : 100,
unit : 2.5
};
//get the addtable function from factory
this.addTable = Service.addTable;
});
here as far as testData is static as follow it works:
this.testData = {
id : '1',
name : "test",
price : 100,
unit : 2.5
};
but here the text in the textbox is not added so I changed the above code as follow:
this.testData = {
id : '1',
name : $("#txt").val(),
price : 100,
unit : 2.5
};
the name gets nothing and row is added but name spot is empty?
Just a quick note that this is a simpler version of my real code and I have a reason to use factory.
Can ahyone help me to find out why this table does not connect to textbox correctly?
Modified version of the plnkr (ooo nice design changes SO).
Updated pasted a bad plnkr link before.
http://plnkr.co/edit/4g7LGRLBNEH2LeuEm1qN?p=preview
code from the post, let me know if this doesn't cover some scenario you were imagining. I tried getting rid of all the style cruft, that should be done in CSS or using things like text-right or text-center provided by bootstrap.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<link data-require="bootstrap#*" data-semver="3.3.1" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<title>Insert title here</title>
<script>
var app = angular.module('app', []);
app.factory('Service', function() {
var typesHash = [ {
id :1,
name : 'lemon',
price : 100,
unit : 2.5
}, {
id : 2,
name : 'meat',
price : 200,
unit : 3.3
} ];
var localId = 3;
var service = {
addTable : addTable,
getData : getData,
};
return service;
function addTable(name) {
typesHash.push({id:localId++, name:name, price:100,unit:1});
}
function getData() {
return typesHash;
}
});
app.controller('table', function(Service) {
//get the return data from getData funtion in factory
this.typesHash = Service.getData();
//get the addtable function from factory
this.addTable = Service.addTable;
});
</script>
</head>
<body ng-app="app" ng-controller="table as tableTools">
<form>
<div class="row commonRow">
<div class="col-xs-1 text-right">
item:
</div>
<div class="col-xs-5">
<input id="txt" type="text" style="width: 100%;" ng-model="tableTools.inputData" />
</div>
<div class="col-xs-2">
<button class="btn btn-primary" ng-click="tableTools.addTable(tableTools.inputData);tableTools.inputData=''">
click me
</button>
</div>
</div>
</form>
<div class="row commonRow">
<div class="col-xs-1"></div>
<div class="col-xs-10">
<table class="table table-hover">
<thead>
<tr>
<th>item</th>
</tr>
</thead>
<tbody ng-controller="table as iterateTb">
<tr ng-repeat="x in iterateTb.typesHash track by x.id">
<td>
<div>{{x.name}}</div>
</td>
<td>
<input type="text" ng-model="x.name"/>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>
here is the updated plunker :-
http://plnkr.co/edit/uDIEAjRtpM7MnQu72LAA?p=preview
I just added data.name=$("#txt").val(); before pushing the data into array.
function addTable(data) {
data.name=$("#txt").val();
typesHash.push(data);
}
Hope it helps :-)
In the following code, when I delete a customer, I want the TR row to disappear.
What is the best way to do this? Do I need to send the row as a parameter to deleteCustomer somehow? Do I have access to the TR DOM element within AngularJS somehow?
<html ng-app="mainModule">
<head>
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body ng-controller="mainController" style="padding: 20px">
<div class="col-lg-5">
<table style="width: 500px" class="table-striped table-bordered table table-hover">
<tr ng-repeat="customer in customers">
<td style="width:50px"><button ng-click="deleteCustomer(customer)">Delete</button></td>
<td style="text-align:right">{{customer.id}}</td>
<td>{{customer.firstName}}</td>
<td>{{customer.lastName}}</td>
</tr>
</table>
</div>
<div class="col-lg-7">
<div class="panel panel-info">
<div class="panel-heading">Logger</div>
<div class="panel-body" style="padding:0">
<table class="table table-bordered" style="margin:0">
<tr ng-repeat="loggedAction in loggedActions">
<td>{{loggedAction.action}}</td>
<td>{{loggedAction.description}}</td>
</tr>
</table>
</div>
</div>
</div>
<script>
var mainModule = angular.module('mainModule', []);
function mainController($scope) {
$scope.loggedActions = [];
$scope.customers = [
{id: 1, firstName: 'Joe', lastName: 'Thompson'},
{id: 2, firstName: 'Hank', lastName: 'Howards'},
{id: 3, firstName: 'Zoe', lastName: 'Frappe'}
];
$scope.deleteCustomer = function (customer) {
$scope.$emit('customerDeleted', customer);
};
$scope.$on('customerDeleted', function (event, customer) {
$scope.loggedActions.push({action: 'delete', description: 'Deleted customer ' + customer.firstName + ' ' + customer.lastName});
});
}
</script>
</body>
</html>
EDIT:
as pointed out by #K.Toress's comment, it's better to retrieve the index of the deleted customer via indexOf() from within the function, rather than passing $index from the ng-repeat.
passing $index will give unexpected results if using a filter or sorting the array.
deleteCustomer function:
$scope.deleteCustomer = function (customer) {
var index = $scope.customers.indexOf(customer);
$scope.customers.splice(index, 1);
$scope.$emit('customerDeleted', customer);
};
updated plnkr
you can use the $index provided by ng-repeat, and array.splice from within the delete function:
html:
<button ng-click="deleteCustomer($index, customer)">Delete</button>
js:
$scope.deleteCustomer = function ($index, customer) {
$scope.customers.splice($index, 1);
$scope.$emit('customerDeleted', customer);
};
plnkr
Working example:
http://plnkr.co/edit/7MOdokoohX0mv9uSWuAF?p=preview
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.data = ['a', 'b', 'c', 'd', 'e'];
$scope.delete = function(at) {
$scope.data.splice(at, 1);
}
});
Template:
<body ng-app="plunker" ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<div ng-repeat="elem in data">
{{elem}}
<button ng-click="delete($index)">delete {{elem}}</button>
</div>
</body>
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