How the AngularJS Controllers Share the Data?

If $scope is said to be the glue between the Controller and the View, and the Controllers are considered as main place where the application functionality exists, so how do the controllers communicate and share the data among themselves.

We’ll be giving you a good idea in this article on How the Controllers in AngularJS share Data among themselves.

Generally it’s always preferred to use one Controller per state. In order to use the States we need to use Angular UI Router. So, lets check out how.

Check out my Plunker

Download Source Code

Index.html – Base file of our code. In this we’ve linked to Bootstrap.css, jQuery library, Angular library, Angular UI router library and app.js.

<html ng-app="app">
<head>
<script src="//code.jquery.com/jquery.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.js"></script>
<script src="app.js"></script>
<style>
  body{
    padding: 40px;
  }
</style>
  <meta charset="utf-8">
  <title>Angular Controller Data Sharing</title>
</head>
<!-- we've replaced the use of $scope with the preferred "controller as" syntax-->
<body>
<ui-view></ui-view>

</body>
</html>

We are using the <ui-view> to access $stateProvider that will configure and provide the data.


Oneview.html


<input type="text" ng-model="oneview.information.message" />
<div ng-class="oneview.information.message">
{{ oneview.information.message }} {{"World"}}
</div>

<div ui-sref="twoview">Go to TwoView</div>

This is the Initial view that’s connected to <ui-view> in the index.html page.


Twoview.html


<h1><b>{{twoview.information.message}}</b> {{"is the actual message we typed in input field on homepage"}}</h1>

This is the state carry forward information of what we’ve typed in the home page.


App.JS – The Controller file. It’s loaded with $stateProvider, service, controller.

angular.module('app', ["ui.router"])
    .config(function config($stateProvider){ //routing between pages
        $stateProvider.state("index", {
            url: "",
            controller:"OneCtrl as oneview",
            templateUrl:"oneview.html"
        })
        $stateProvider.state("twoview", {
            url: "/twoview",
            controller:"TwoCtrl as twoview",
            templateUrl:"twoview.html"
        })
    })

    .service("information", function Information(){
        var information = this;

        information.message = "Default";
    })

    .controller('OneCtrl', function OneCtrl(information) {
        var oneview = this;

        oneview.information = information;

    })
    .controller('TwoCtrl', function TwoCtrl(information) {
        var twoview = this;

        twoview.information = information;
    });

Output: 

AngularJS controllersangularjs controllers sharing data

Its a pretty straight forward process that will help you to understand how the Controllers in AngularJS tend to share data and communicate with each other by maintaining the state.

Simple Pagination using PHP – Tutorial

I’ve received an email from one of our reader, he has requested for a tutorial on Simple Pagination using PHP. If you have a website with large amount of data, for instance some 100 rows of tabular data. It will be quite painful for the user, if all the 100 rows of data is being displayed in the same page, instead if we show 10 records per page it will enhance user experience.

The procedure we follow here is, first we have declare a variable $reclimit and assigned a value 10 in order to display 10 records. Next we need to calculate the starting record number using $start = $page-1 * $reclimit (We get the current page number from the URL querystring). Total number of records is stored in $total variable which is obtained from num_rows. Using this total variable, we will obtain the total number of pages. Next using a for loop we will display Page Numbers.

simple pagination php

Download Source Code

We’ve used a sample employees table for this tutorial.

Simple Pagination using PHP

<html>
<body>
<?php
	$mysqli = mysqli_connect("localhost","root","password","mydb");
	$reclimit = 3;
	
	if(isset($_GET['page'])){
		$page = $_GET['page'];
	} else {
		$page = 1;
	}

	$start = (($page-1) * $reclimit);
	$sql = "SELECT * FROM employee";
	$records = $mysqli->query($sql);
	$total = $records->num_rows;
	$tpages = ceil($total / $reclimit);
	$rec = "SELECT * FROM employee ORDER BY first_name ASC LIMIT $start, $reclimit";
	$records = $mysqli->query($rec);
	?>
				<table border="0">
					<thead>
						<tr>
							<td><b>First Name</b></td>
							<td><b>Last Name</b></td>
							<td><b>Job Title</b></td>
							<td><b>Salary</b></td>
						</tr>
					</thead>
					<tbody>
						<?php
							while($row = $records->fetch_array()) {
								echo "<tr>";
								echo "<td>".$row['first_name']."</td>";
								echo "<td>".$row['last_name']."</td>";
								echo "<td>".$row['job_title']."</td>";
								echo "<td>".$row['salary']."</td>";
								echo "</tr>";
							}

						?>
					</tbody>
				</table>
				<ul class="pagination">
					<?php
						for($i=1;$i<=$tpages;$i++) {
							echo "<li><a href=index.php?page=".$i.">".$i."</a></li>";
						}
					?>
				</ul>
</body>
</html>

Check Username Availability using PHP and jQuery

When you have a user registration form, you need to prevent duplicate usernames. In this tutorial we will be providing a sample code for Checking username availability using PHP and jQuery. As two users cannot have the same username, during registration process of the user we need check whether the requested username is available or not. If it is available the user can continue registration process else they need to choose another username. It would be easy for the user when we check the availability of username in the registration page itself instead of throwing an error after filling all the details.

Check_Username_Availability

The process flow is, User enters registration page and gives the input of the desired username and clicks on check availability – this triggers Click event and checks if the desired Username exists in the Database. If it exists, then an error is thrown.

DemoDownload Source Code

Register.php

<html>
<body>
<table border="0">
	<form method="POST" action="register.php" id="regform">
		<tr>
			<td colspan="2">Password will be sent via Email.</td>
		</tr>
		
		<tr>
			<td>Username:</td>
			<td><input type="text" placeholder="Username" id="username"><a id="checkavail">Check Availability</a></td>
		</tr>

		<tr>
			<td>Email:</td>
			<td><input type="email" placeholder="Email" id="email"></td>
		</tr>
		<tr>
			<td colspan="2"><input type="submit" id="sign" value="Register"></td>
		</tr>
	</form>
</table>
<script src="jquery-2.1.3.min.js"></script>
<script src="CheckUser.js"></script>
</body>
</html>

CheckUser.js

$(function(){
	$("#checkavail").click(function(){
		var uname = $("#username").val();
		$.ajax({
		  type: "POST",
		  url: 'check.php',
		  data: {uname:uname},
		  success: function(d){
		  	if(d==-1){
		  		$('#username').css("border", "1px solid red");
		  		$('#username').focus();
		  		$("#message").toggle();
		  		$("#sign").attr('disabled', 'disabled');
		  		$("#regform").submit(function(e){
		  			e.preventDefault();
		  		});
		  	}
		  	if(d==1){
		  		$('#username').css("border", "1px solid green");
		  		$('#message').css('display', 'none');
		  		$('#sign').removeAttr('disabled');
		  	}
		  }
		});
		
	});
});

check.php

<?php
//Check.php file contains SQL query to check availability of username 
//in the Database
$mysqli = mysqli_connect("localhost","root","my_password","my_db");

$check = $_POST['uname'];

$sql = "SELECT username FROM users WHERE username='$check'";
$records = $mysqli->query($sql);

$recCount = $records->num_rows;

if($recCount>0) {
	echo -1;
}

else {
	echo 1;
}

?>

If you have any queries, please let us know them in the comments section.

Learn about the Concept of Scope in Javascript

Scope is one of the most important topics in JavaScript. The best way to define scope of a variable/function is “it determines the accessibility of the specific variable/function”. It can be divided into limitless amount of levels like Global Scope -> Sub Scope -> Baby Sub Scope and so on. As the name reflects that Global Scope is globally accessible.

Other than Global scope, we need to know about the Local Scope as well, in which the variables/functions are only limited to that specific local function in which they are defined and cannot be accessed from it’s parent.

I hope that gives the required information about the scope. I’m here to explain you with best possible scenarios that will give you even better understanding about the Scope concept in the JavaScript.

march-3x-24x-FFP-6x

 Explaining Concept of Scope in JavaScript:

 var globalVariable = "This is a global variable.";

var globalFunction = function() {
alert(globalVariable);
globalVariable = "I have changed the value here";
};

globalFunction();
alert(globalVariable);  

What’s the output: First alert box pops-up saying “This is a global variable” followed by second alert box saying “I have changed the value here”. This shows that we can access the global variables from anywhere in our code and the scope of the global function/variable will always be globally accessible.

learn about scope local scope in javascript

var globalVariable = "This is a global variable.";

var globalFunction = function() {
var localVariable = "This is a local variable"; //local variable inside the function scope
alert(localVariable);
globalVariable ="I modified the global variable";
};

globalFunction();
alert(localVariable); //local variable outside the function scope
alert(globalVariable);  

What’s the output : The globalFunction() gets invoked and displays the alert(localVariable) in the alert box “This is the local variable” and after that you will notice nothing happens, because the Javascript controller comes out of the function and trying to search for the alert(localVariable) outside the function and fails. Once the first alert fails, the Javascript engine stops executing the code, for which alert(globalVariable) doesn’t gets executed. This is one of the best example explaining local scope of the variables.

local variable scope
A similar example by passing the parameter in the function.

var globalVariable = "This is a global variable.";

var globalFunction = function(parameter) {
var localVariable = "This is a local variable";
alert(parameter);
globalVariable ="I have changed the value here";

};

globalFunction(11);
alert(parameter);
alert(globalVariable);  

What’s the output : considering the parameter value 11 which we passed inside the function it alerts 11 in the first instance, and then breaks as the parameter scope is just limited to the function.

javascript scope

Let's make things bit more complicated here.
var globalVariable = "This is a global variable.";

var globalFunction = function() //parent function {
var localFunction = function() //child function {
var childLocalVariable = "This is the super child local variable.";
alert(childLocalVariable);

};
localFunction();
alert(childLocalVariable); //trying to access child function's variable from parent function.

};

globalFunction();
alert(childLocalVariable);
alert(globalVariable);  

What’s the output : globalFunction() gets invoked, and the controller enters localFunction() and then alerts “This is the super child local variable” and comes out of the child function [localFunction()], and tries to alert the variable in the child function from the parent function [globalFunction()] and breaks the execution at that point.

child scope of local function

var globalVariable = "This is a global variable.";

var globalFunction = function(parameter) {
var localVariable = "This is a local variable";

var localFunction = function() {
var childLocalVariable = "This is the super child local variable.";

alert(childLocalVariable);
alert(localVariable);
alert(parameter);
alert(globalVariable);

};
localFunction();

};

globalFunction(11); 

What’s the Output : globalFunction(11) gets invoked and the controller enters into localFunction() and starts alerting “This is the super child local variable”, followed by “This is a local variable”, followed by “11” and then “This is a global variable”. The reason it’s able to display all alerts is because the scope where we are trying to access the alert is inside the child function. So, this stats us the child function can access all variables/functions of the parent, but the vice versa is not possible.

child scope of local function
local variable scope
javascript scope
learn about scope

For even better understanding, I’m adding few youtube videos that will definitely help you to gain more knowledge about the Concept of Scope in Javascript.

Hope you learnt something about Javascript Scope, stay tuned for more updates.

Basics you need to know about Cisco Packet Tracer [Download]

If you are searching for best and basic Cisco Packet Tracer Tutorials online, then this is going to be the one stop post for you! We are also going to provide you the Cisco Packet Tracer Download path as well with which you can have the hands-on experience.

The Other day, I was assigned with an assignment by our Network Professor (based on Cisco Packet Tracer) and I wasn’t aware of what exactly is going on and how am I supposed to finish it, as I was completely confused with the terms like Default Gateway, Subnetting, Broadcast Address, DNS Servers, Switches, Hubs, Routers, and what not, everything looked pretty miserable. I didn’t even have Cisco Packet tracer download file on my system either.

cisco packet tracer tutorialsI decided that I have to work it out somehow and I called few of my friends to get done it by means of combined study, but somehow it didn’t work-out well for me and I was completely broken, not knowing what to do, as the pressure creeping on me like hell as I thought I was wasting too much time and I got to learn it as early as I can.

I’ve started going through the materials and everything looked cluttered as none of them answered my questions. I got to search for references online and many other stuff for each and every topic individually and luckily, a Youtube Channel which is based on Cisco Packet Tracer configuration tutorials answered each and every question that I have.

So, I thought of sharing those videos, in order to help you out with it and save your valuable time helping you to learn and also help you find cisco packet tracer download file. I must thank dancourses Channel for helping me out by providing such a wonderful video series.

Before checking out the tutorials, lets find out how we can find the Cisco Packet Tracer Download file.

You need to sign-up/login into Cisco NetSpace web-portal initially. Now you need to select the CCNA option followed by Cisco Packet Tracer which you can find in the Offerings menu.

These are some of the best videos to get started with Packet Tracer and I assure you that you will learn many technical terms that you aren’t aware before getting started with networking course.

Hope you enjoyed my article on how to find Cisco Packet Tracer download file and how to get started with Packet Tracer Tutorials and stay tuned for more exciting stuff.