AngularJs: store and retrieve data in local storage - angularjs

I am very new to Angular. Earlier I was using Javascript, but now I am learning AngularJs. Version currently using is 1.3.2.
Problem is I am trying to use local storage.
In Javascript, we use something similar to this:
localStorage.pic = data.pic;
localStorage.id = data.uid;
localStorage.name = data.name;
Is there anything similar to this in AngularJs?
Thanks for your advise.

It's the same way using ngStorage,
Add ngStorage reference and inject it as a depdency to your angular app,
<script type="text/javascript" src='https://rawgithub.com/gsklee/ngStorage/master/ngStorage.js'></script>
angular.module('gameApp', ['ngStorage'])
Then you can store and retrieve like this,
$localStorage.pic= $scope.pic;
DEMO
angular.module('gameApp', ['ngStorage', 'ui.bootstrap'])
.controller('MainCtrl', ['$scope', '$localStorage', function ($scope, $localStorage) {
// Set a total score variable equal to zero
$scope.total = 0;
// NOTE: use d3.js for data visualization in widget
var gameData = [
{
"level": "Level One",
"points": 30,
"max": 100,
"completed": false
},
{
"level": "Level Two",
"points": 50,
"max": 100,
"completed": false
}
];
// tie the game JSON to the view
$scope.gameData = gameData;
// tie the view to ngModule which saves the JSON to localStorage
$localStorage.gameData = gameData;
// loop through the gameData and sum all the values where the key = 'points'
console.log("Your current score is: " + $scope.total)
$localStorage.total = $scope.total;
$scope.addToLevel = function(level, num){
$scope.levelPoints = gameData[level].points += num;
console.log("You have " + $scope.levelPoints + " points in Level");
}
// create a function that loops the json to check if the points >= max
// and if so
// then change completed to true
$scope.calcTotal = function(){
for (var i in $scope.gameData){
var level = $scope.gameData[i];
$scope.total += level.points;
}
$localStorage.total = $scope.total;
};
$scope.calcTotal();
}])
<!DOCTYPE html>
<html ng-app='gameApp'>
<head>
<meta charset="utf-8" />
<title>Angular Local storage</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">
<script type="text/javascript" src='https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js'></script>
<script type="text/javascript" src='https://rawgithub.com/gsklee/ngStorage/master/ngStorage.js'></script>
<script src="https://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.12.1.js"></script>
<script type="text/javascript" src='script.js'></script>
</head>
<body ng-controller='MainCtrl'>
<!-- Fixed navbar -->
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Angular JS Local Storage</a>
</div>
</div>
</nav>
<div class='container'>
<div class='row' style='margin-top:100px'>
<button class='btn btn-primary' ng-click="addToLevel(0, 20); calcTotal();">+20 Points Lvl 1</button>
<br>
<table class='table table-hover'>
<thead>
<tr>
<td>Level</td>
<td>Points</td>
</tr>
</thead>
<tbody>
<tr ng-repeat='data in gameData'>
<td>{{ data.level }}</td>
<td>{{ data.points }}</td>
</tr>
<tr>
<td>Total Points</td>
<td>{{total}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>

You can create a common factory service that will save and return the saved local storage data based on the key.
app.factory('storageService', ['$rootScope', function($rootScope) {
return {
get: function(key) {
return localStorage.getItem(key);
},
set: function(key, data) {
localStorage.setItem(key, data);
}
};
}]);
In controller :
Inject the storageService dependency in the controller to set and get the data from the local storage.
app.controller('myCtrl',['storageService',function(storageService) {
// Set local storage data to storageService
storageService.set('key', 'value');
// Get saved local storage data from storageService
var data = storageService.get('key');
});

JavaScript will remain same whether you use angular or other frameworks.You are doing wrong , localStorage has setItem() and getItem() methods .
Try this
localStorage.setItem('pic',data.pic);
localStorage.setItem('id',data.id);
localStorage.setItem('name',data.name);
And retrieval like this
localStorage.getItem('pic');
localStorage.getItem('id');
localStorage.getItem('name');

Related

Updating the view with respect to number of clicks in angularjs

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>

How to add pagination using angular js in datatable

**How to add pagination using angular js in jquery Datatable plugin. There is some external plugin available like angular js data table that directly allows pagination but i want to make inside jquery data table. **
var app= angular.module("myModule",['ui-bootstrap']);
app.controller("dataController",function($scope,$http){
$http({
method: 'GET',
url: 'https://api.myjson.com/bins/833qv'
}).then(function successCallback(response) {
$scope.employees=response.data;
console.log($scope.employees);
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<title>Angula js | Home </title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
<div ng-app="myModule">
<input type="text" ng-model="searchFilter" />
<div ng-controller="dataController">
<table style="width:500px;border:2px solid black;">
<thead>
<tr style="text-align:left;">
<th>Id</th>
<th>Client name</th>
<th>Client code</th>
<th>Team id</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="employee in employees">
<td>{{employee.id}}</td>
<td>{{employee.client_name}}</td>
<td>{{employee.client_code}}</td>
<td>{{employee.team_id}}</td>
</tr>
</tbody>
</table>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.min.js"></script>
<script src="custom.js"></script>
</body>
</html>
its not accepting datatable pagination. can it possible that angular js accept datatable jqyery pagination.
Pagination:
HTML part
<ul>
<li class="paginationclass" style="font-weight:bold;"><span>Name</span><span>Age</span><span>Designation</span></li>
<li class="paginationclass" ng-repeat="datalist in datalists | pagination: curPage * pageSize | limitTo: pageSize">
<div><span>{{ datalist.name }} </span><span>{{ datalist.age }}</span><span>{{ datalist.designation }}</span></div>
</li>
</ul>
<div class="pagination pagination-centered" ng-show="datalists.length">
<ul class="pagination-controle pagination">
<li>
<button type="button" class="btn btn-primary" ng-disabled="curPage == 0"
ng-click="curPage=curPage-1"> < PREV</button>
</li>
<li>
<span>Page {{curPage + 1}} of {{ numberOfPages() }}</span>
</li>
<li>
<button type="button" class="btn btn-primary"
ng-disabled="curPage >= datalists.length/pageSize - 1"
ng-click="curPage = curPage+1">NEXT ></button>
</li>
</ul>
</div>
</div>
</div>
JS part
var myapp = angular.module('sampleapp', [ ]);
myapp.controller('samplecontoller', function ($scope) {
$scope.showData = function( ){
$scope.curPage = 0;
$scope.pageSize = 3;
$scope.datalists = [
{ "name": "John","age":"16","designation":"Software Engineer1"},
{"name": "John2","age":"21","designation":"Software Engineer2"},
{"name": "John3","age":"19","designation":"Software Engineer3"},
{"name": "John4","age":"17","designation":"Software Engineer4"},
{"name": "John5","age":"21","designation":"Software Engineer5"},
{"name": "John6","age":"31","designation":"Software Engineer6"},
{"name": "John7","age":"41","designation":"Software Engineer7"},
{"name": "John8","age":"16","designation":"Software Engineer8"},
{"name": "John18","age":"16","designation":"Software Engineer9"},
{"name": "John28","age":"16","designation":"Software Engineer10"},
{"name": "John38","age":"16","designation":"Software Engineer11"},
{"name": "John48","age":"16","designation":"Software Engineer12"},
{"name": "John58","age":"16","designation":"Software Engineer13"},
{"name": "John68","age":"16","designation":"Software Engineer14"},
{"name": "John68","age":"16","designation":"Software Engineer15"}
]
$scope.numberOfPages = function() {
return Math.ceil($scope.datalists.length / $scope.pageSize);
};
}
});
angular.module('sampleapp').filter('pagination', function()
{
return function(input, start)
{
start = +start;
return input.slice(start);
};
});
Use this open source library basically enhanced version of JQuery DataTables to rendered tables which include pagination, sorting, searching and filtering and very good support of accessibility.
https://assets.cms.gov/resources/framework/2.0/Pages/datatables.html.

Angular two way data-binding dosn´t update table in different route

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;

How to delete the row in which a ng-click is located?

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>

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