Background

AngularJS is an open source framework, designed for the creation of enhanced web applications, created by Miško Hevery at Brat Tech LLC, and maintained by Google plus a community of developers and corporations. It implements most of the concepts behind all new standards on web components and model driven views. This framework is in the category of data binding frameworks.

You can create single page applications in which the page doesn’t required to reload, by using XML, JSON plus AJAX to fetch data, and without using server-side rendering. You follow a simple concept called Model-View-Controller in which the data taken care by the model (database, file, etc.), the view take cares of everything related with the interaction with the user, and the controller takes care of the communication between the model and the view. Another way to describe this concept is the idea that the model updates the view, the view display the information to the user, the user interact with the controller via the view, and the controller manipulates the model.

MVC-ConceptIt is important to indicate that AngularJS uses data binding which means that there is a synchronization between the model an the user interface. That, it implements routing, a way to handle updates by using URL hash fragments. Finally, by using templates and model, it allows for the dynamically creating and update of HTML.


 

Example 1
Try:

Source Code:
<!DOCTYPE html>
<html ng-app>
<head>
<meta charset="UTF-8">
<title>AngularJS - Example 1</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.0/angular.min.js"> </script>
</head>
<body>
Type your name: <input ng-model="name" type="text" />
Hello, {{'{{name}\}'}}
</body>
</html>

 

Example 2:

Try:

Source Code:

<!DOCTYPE html>
<html ng-app>
<head>
<meta charset="UTF-8">
<title>AngularJS - Example 2</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.0/angular.min.js"> </script>
<script>	
	// From Angular 1.3, you must use allowGlobals if you wish to use
	// global controller declaration without explicit registration
	// on the global scope.
	angular.module("ng").config(function($controllerProvider){
		$controllerProvider.allowGlobals();
	});
	
	function NameController($scope){
		$scope.firstName = 'Alex';
		$scope.lastName = 'Ramod';
	}
</script>
</head>
<body ng-controller="NameController">
First Name: <input ng-model="firstName" type="text" /><br>
Last Name: <input ng-model="lastName" type="text" /><br>
Hello, {{'{{firstName}\}'}} {{'{{lastName}\}'}}
</body>
</html>

 

Example 3:

Try:

Source Code:

<!DOCTYPE html>
<html ng-app="thisApp">
<head>
<meta charset="UTF-8">
<title>AngularJS - Example 3</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.0/angular.min.js"> </script>
<script>	
	var thisApp = angular.module('thisApp', []);
	thisApp.controller('NameController', function NameController($scope){
		$scope.firstName = 'Alex';
		$scope.lastName = 'Ramod';
	});
</script>
</head>
<body ng-controller="NameController">
First Name: <input ng-model="firstName" type="text" /><br>
Last Name: <input ng-model="lastName" type="text" /><br>
Hello, {{'{{firstName}\}')) {{'{{lastName}\}'}}
</body>
</html>

 

Example 4:

Try:

Source Code:

<!DOCTYPE html>
<html ng-app="thisApp">
<head>
<meta charset="UTF-8">
<title>AngularJS - Example 4</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.0/angular.min.js"> </script>
<script>	
	var thisApp = angular.module('thisApp', []);
	
	thisApp.controller('thisController', function NameController($scope){
		$scope.firstName = 'Alex';
		
		$scope.$watch('lastName', function(newValue, oldValue){
			console.log('--- $watch ---');
			console.log('Old value: ' + oldValue);			
			console.log('New value: ' + newValue);
			console.log('--------------');
		});
		
		setTimeout(function(){
			$scope.lastName = "Ramod";
			$scope.$apply();
		}, 1000);
	});
</script>
</head>
<body ng-controller="thisController">
First Name: <input ng-model="firstName" type="text" /><br>
Last Name: <input ng-model="lastName" type="text" /><br>
Hello, {{'{{firstName}\}'}} {{'{{lastName}\}'}}
</body>
</html>

Console Output:

--- $watch ---
Old value: undefined
New value: undefined
--------------
--- $watch ---
Old value: undefined
New value: Ramod
--------------

 

Example 5:

Try:

<!DOCTYPE html>
<html ng-app="thisApp">
<head>
<meta charset="UTF-8">
<title>AngularJS - Example 5</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.0/angular.min.js"> </script>
<script>	
	var thisApp = angular.module('thisApp', []);
	
	thisApp.controller('employeesController', function NameController($scope){
		
		$scope.employeeNames = ['Diego', 'Marina', 'Marc'];
		
		$scope.addEmployeeName = function() {
			$scope.employeeNames.push($scope.enteredEmployeeName);
			$scope.enteredEmployeeName = "";
		}
		
		$scope.removeEmployeeName = function(employeeName){
			var index = $scope.employeeNames.indexOf(employeeName);
			$scope.employeeNames.splice(index, 1);
		}
		
	});
</script>
</head>
<body ng-controller="employeesController">

	<form name="employeeNameForm" ng-submit="addEmployeeName()">
		Employee Name: <input name="employeeNameTextBox" 
							  ng-model="enteredEmployeeName"
							  type="text" 
							  required />		
		<input type="submit" value="add">
		<div role="alert">
			<span class="error" ng-show="employeeNameForm.employeeNameTextBox.$error.required">
				* The employee name cannot be empty
			</span>
		</div>	
	</form>
	<ul>
		<li ng-repeat="employeeName in employeeNames">
			{{'{{employeeName}\}'}} <a href="" ng-click="removeEmployeeName(employeeName)">[Remove]</a>
		</li>
	</ul>

</body>
</html>

 

Example 6:

Try:

Source Code:

<!DOCTYPE html>
<html ng-app="thisApp">
<head>
<meta charset="UTF-8">
<title>AngularJS - Example 6</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.0/angular.min.js"> </script>
<script>	
	var thisApp = angular.module('thisApp', []);
	
	thisApp.controller('countriesController', function NameController($scope){
		
		// We will fetch this data in the next example using JSON
		$scope.countries = [
			{"name": "The United States", "state": "Colorado"},
			{"name": "The United States", "state": "Florida"},
			{"name": "The United States", "state": "New York"},
			{"name": "Argentina", "state": "Buenos Aires"},
			{"name": "Argentina", "state": "Pellegrini"},
			{"name": "Uruguay", "state": "Carmelo"},
			{"name": "Uruguay", "state": "Colonia"},
			{"name": "Uruguay", "state": "Conchillas"}
		];
		
		$scope.sortField = 'name';
		$scope.reverse = true;
		
	});
</script>
</head>
<body ng-controller="countriesController">
	Search: <input ng-model="query" type="text" />
	<table border="1">
		<tr>
			<th><a href="" ng-click="sortField = 'name'; reverse = !reverse">Country</a></th>
			<th><a href="" ng-click="sortField = 'state'; reverse = !reverse">State/Provincia</a></th>
		</tr>
		<tr ng-repeat="country in countries | filter: query | orderBy: sortField:reverse">
			<td>
				{{'{{country.name}\}'}}
			</td>
			<td>
				{{'{{country.state}\}'}}
			</td>
		</tr>		
	</table>
	<br>
</body>
</html>

 

Example 7:

Try:

Source Code:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>AngularJS - Example 7</title>
<style>
    @import url('http://getbootstrap.com/2.3.2/assets/css/bootstrap.css');
    
    ul {
        margin: 0;
        padding: 0;
        list-style-type: none;
        text-align: center;
    }
    
    ul li { display: inline; }
</style>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.0/angular.min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js"></script>
 
<script>    
    var thisApp = angular.module('thisApp', []);
 
    // Controllers
    var TableController = thisApp.controller('TableController', function ($scope, $http, $filter, serviceFilteredList) {
     
        $scope.pageSize = 4;
        $scope.reverse = false;           
       
        $scope.selectedItems =  [
                                    {numOfRows: 4, text: "4 rows"},
                                    {numOfRows: 3, text: "3 rows"},
                                    {numOfRows: 2, text: "2 rows"},
                                    {numOfRows: 1, text: "1 row"},                                                                        
                                ];
                                
        $scope.allItems = getEmptyData();
           
        $scope.getCountriesFromUrl = function($scope, $http, url){
            $http.get(url).success(function(data, status, headers, config){
                console.log("[!] Success:");
                $scope.allItems = data;
                $scope.sort();
            }).error(function(data, status, headers, config){
                var errorMessage = "[!] Failure:"
                                 + "    -> Headers: " + headers
                                 + "    -> Status: "+ status
                                 + "    -> Config: "+ config
                                 + "    -> Data: "+ data;
                console.log(errorMessage);
            });            
        }
    
        var url = "https://raw.githubusercontent.com/astockwell/countries-and-provinces-states-regions/master/countries.json";
        $scope.getCountriesFromUrl($scope, $http, url);       
        
        $scope.add = function () {
            $scope.allItems.push({
                code: $scope.newCode,
                name: $scope.newName,
                continent: $scope.newContinent
            });
            $scope.resetAll();
        }
        
        $scope.resetAll = function () {
            $scope.filteredList = $scope.allItems;
            $scope.newCode = '';
            $scope.newName = '';
            $scope.newContinent = '';
            $scope.Header = ['','',''];
            $scope.currentPage = 0;
            $scope.searchText = '';
        }
        
        $scope.search = function () {
            $scope.filteredList = serviceFilteredList.searched($scope.allItems, $scope.searchText);
            
            if ($scope.searchText == '') {
                $scope.filteredList = $scope.allItems;
            }
            
            $scope.pagination(); 
        }
    
        $scope.range = function (input, total) {
            var ret = [];
            
            if (!total) {
                total = input;
                input = 0;
            }
            
            for (var i = input; i < total; ++i) {
                if (i != 0 && i != total - 1) {
                    ret.push(i);
                }
            }
            
            return ret;
        };        
        
        $scope.pagination = function () {
            $scope.ItemsByPage = serviceFilteredList.paged( $scope.filteredList, $scope.pageSize );         
        };
    
        $scope.setPage = function () {
            $scope.currentPage = this.n;
        };
    
        $scope.firstPage = function () {
            $scope.currentPage = 0;
        };
    
        $scope.lastPage = function () {
            $scope.currentPage = $scope.ItemsByPage.length - 1;
        };
    
        
        $scope.sort = function(sortBy){
            $scope.resetAll();  
            
            $scope.columnToOrder = sortBy; 
                 
            $scope.filteredList = $filter('orderBy')($scope.filteredList, $scope.columnToOrder, $scope.reverse); 
                                   
            $scope.reverse = !$scope.reverse;   
            
            $scope.pagination();    
        };
        
        $scope.$watch("display", function(newValue, oldValue){            
            $scope.pageSize = parseInt(newValue.numOfRows);
            $scope.sort()
        });
        
      $scope.display = $scope.selectedItems[0];
                
    });

    // Services
    thisApp.service('serviceFilteredList', function () {
        
        this.searched = function (listsOfValues, toSearch) {
            return _.filter(listsOfValues, function (i) {
                return searchInAllFields(i, toSearch);
            });        
        };
    
        this.paged = function (listsOfValues, pageSize) {
            retVal = [];
            if (undefined !== listsOfValues) {
                for (var i = 0; i < listsOfValues.length; ++i) {
                    var pageIndex = Math.floor(i / pageSize) 
                    if (i % pageSize === 0) {
                        retVal[pageIndex] = [listsOfValues[i]];
                    } else {
                        retVal[pageIndex].push(listsOfValues[i]);
                    }
                }
            }
            return retVal;
        };
 
    });

    //Inject Services
    TableController.$inject = ['$scope', '$filter','serviceFilteredList'];
    
    function searchInAllFields(item, toSearch) {     
        return (item.name.toLowerCase().indexOf(toSearch.toLowerCase()) > -1 || 
                item.continent.toLowerCase().indexOf(toSearch.toLowerCase()) > -1 || 
                item.continent.toLowerCase().indexOf(toSearch.toLowerCase()) > -1) ? true : false;
    }
        
    function getEmptyData() { return [{}]; }
    
</script>
</head>
<body>
 
    <div ng-app="thisApp">
        <div ng-controller="TableController">
            <div class="input-group">
                Search: <input ng-model="searchText" 
                               ng-change="search()" 
                               placeholder="Search in all fields" 
                               type="search" 
                               class="form-control" /> 
            <span>
                <span>
                     Display: <select id="displaySelect"
                                       name="displaySelect"
                                       ng-model="display"
                                       ng-options="display as display.text for display in selectedItems">                                        
                              </select>                    
                </span>
            </span>
         </div>
         <table class="table table-hover data-table">
            <thead>
                <tr>
                    <th class="name"> 
                        <a ng-click="sort('name')" href="#"> 
                            Country <span class="{{Header[1]}}"></span>
                        </a> 
                    </th>
                    <th class="code"> 
                        <a href="#" ng-click="sort('code',$event)">
                            Code <span class="{{Header[0]}}"></span>
                        </a>
                    </th>
                    <th class="continent"> 
                        <a ng-click="sort('continent')" href="#"> 
                            Continent <span class="{{Header[2]}}"></span>
                         </a> 
                    </th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="item in ItemsByPage[currentPage] | orderBy:columnToOrder:reverse">
                    <td>{{item.name}}</td>
                    <td>{{item.code}}</td>
                    <td>{{item.continent}}</td>
                </tr>
            </tbody>
        </table>
        <ul id="navcontainer" name="navcontainer" class="pagination pagination-sm">
            <li ng-class="{active:0}">
                <a href="#" ng-click="firstPage()">First</a>
            </li>
            <li ng-repeat="n in range(ItemsByPage.length)"> 
                <a href="#" ng-click="setPage()" ng-bind="n + 1">1</a>
            </li>
            <li>
                <a href="#" ng-click="lastPage()">Last</a>
            </li>
        </ul>
        
    </div>

</body>
</html>

 

 

 

© 2015, Alejandro G. Carlstein Ramos Mejia. All rights reserved.

Share

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

*

Click to Insert Smiley

SmileBig SmileGrinLaughFrownBig FrownCryNeutralWinkKissRazzChicCoolAngryReally AngryConfusedQuestionThinkingPainShockYesNoLOLSillyBeautyLashesCuteShyBlushKissedIn LoveDroolGiggleSnickerHeh!SmirkWiltWeepIDKStruggleSide FrownDazedHypnotizedSweatEek!Roll EyesSarcasmDisdainSmugMoney MouthFoot in MouthShut MouthQuietShameBeat UpMeanEvil GrinGrit TeethShoutPissed OffReally PissedMad RazzDrunken RazzSickYawnSleepyDanceClapJumpHandshakeHigh FiveHug LeftHug RightKiss BlowKissingByeGo AwayCall MeOn the PhoneSecretMeetingWavingStopTime OutTalk to the HandLoserLyingDOH!Fingers CrossedWaitingSuspenseTremblePrayWorshipStarvingEatVictoryCurseAlienAngelClownCowboyCyclopsDevilDoctorFemale FighterMale FighterMohawkMusicNerdPartyPirateSkywalkerSnowmanSoldierVampireZombie KillerGhostSkeletonBunnyCatCat 2ChickChickenChicken 2CowCow 2DogDog 2DuckGoatHippoKoalaLionMonkeyMonkey 2MousePandaPigPig 2SheepSheep 2ReindeerSnailTigerTurtleBeerDrinkLiquorCoffeeCakePizzaWatermelonBowlPlateCanFemaleMaleHeartBroken HeartRoseDead RosePeaceYin YangUS FlagMoonStarSunCloudyRainThunderUmbrellaRainbowMusic NoteAirplaneCarIslandAnnouncebrbMailCellPhoneCameraFilmTVClockLampSearchCoinsComputerConsolePresentSoccerCloverPumpkinBombHammerKnifeHandcuffsPillPoopCigarette