Introduction to AngularJS Framework (with Key Concepts)
By Hamid Akhtar, Community Contributor - May 12, 2023
HTML is an effective declarative language for creating static documents. The framework lacks sufficient support for application development, leading to the need for workarounds to achieve desired browser behavior when building web applications.
By creating new HTML constructs, AngularJS framework attempts to reduce the gap between document-centric HTML and application requirements.
- What is AngularJS Framework?
- Benefits of using AngularJS Framework
- General Features of Angular JS Framework
- Key Concepts of AngularJS Framework
- Setting up an AngularJS Environment
- Components of an AngularJS Application
- Working with AngularJS Directives
- Controllers in AngularJS
- Services in AngularJS
- How to test an AngularJS web application on BrowserStack?
What is AngularJS Framework?
AngularJS framework is used for creating dynamic web apps with a structural architecture. This framework enables using HTML as the template language and facilitates the extension of HTML’s syntax to express application components clearly and concisely.
Features such as Data binding and dependency injection reduce the code required. The whole process occurs solely within the browser, rendering it a suitable complement to any server technology.
With this JavaScript MVC framework, you can effortlessly craft dynamic web applications packed with features and experience the multitude of benefits it offers, empowering developers to create web applications that are both user-friendly and engaging and captivating.
Also Read: Angular vs AngularJS
Benefits of using AngularJS Framework
- No prerequisite required: AngularJS is designed to be compatible with HTML, CSS, and JavaScript. Learning a new scripting language is unnecessary. Also, HTML, CSS, and JavaScript are relatively simple to pick up, even if you don’t know them already.
- Simple to expand: because of several built-in features, HTML’s functionality may be increased by coupling a particular behavior. It is customized since one may add their own directives to it.
- Excellent MVC: To implement the Model-View-Controller (MVC) architecture, many frameworks need the code to be broken up into separate MVC components (Model, View, and Controller). The process is fully automated in Angular. Angular helps programmers save time by organizing their code.
- Simple for Testing: Angular is written in the dynamically typed JavaScript language. The expressive potential of angular is immense. However, Angular does not come with a compiler. Therefore, a solid test code for it must be written. Unit testing will be much simpler because it has a dependency injection built right in. Angular is compatible with both unit tests and system tests.
- TypeScript, a Microsoft-managed programming language, is the foundation for the Angular framework. Because it serves as Angular’s base language and is strongly typed, it helps developers avoid messy code. A program with such pristine code should run smoothly and efficiently.
Example of AngularJS
<!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script> <body ng-app="BrowserstackApp" ng-controller="myNoteCtrl"> <h2>BrowserStackNote</h2> <textarea ng-model="message" cols="40" rows="10"></textarea> <p> <button ng-click="save()">Save</button> <button ng-click="clear()">Clear</button> </p> <p>Number of characters left: <span ng-bind="left()"></span></p> <script> var app = angular.module("myNoteApp", []); app.controller("myNoteCtrl", function($scope) { $scope.message = ""; $scope.left = function() { return 100 - $scope.message.length; }; $scope.clear = function() { $scope.message = ""; }; $scope.save = function() { alert("Note Saved"); }; }); </script> </body> </html>
General Features of Angular JS Framework
AngularJS has the following general features:
- Angularjs is a proficient framework for developing Rich Internet Applications (RIA).
- It enables developers to create client-side applications using JavaScript in a structured Model-View-Controller (MVC) pattern.
- AngularJS applications are compatible with multiple web browsers. AngularJS automatically manages cross-browser JavaScript code.
- It is a widely used open-source and has a global developer community.
- It is a framework for developing web applications that are scalable, high-performing, and easily maintainable.
Key Concepts of AngularJS Framework
1. Data binding
Data binding controls page elements such as headings, text, and images. It bridges the gap between an app’s user interface and underlying data. It is possible to make changes on the model side and have them instantly mirrored on the view side, and vice versa. This is done so swiftly to ensure that the view and the model part are constantly updated.
- Adding a few lines of AngularJS code may connect the model and view parts.
- To do this, a concept known as directives is used.
- This allows you to link the value of a header or input field (a web component) to an HTML element. ng-bind is one of the directives that may be used to do this.
<div ng-app="BrowserStackApp" ng-controller="myCtrl"> <h3 ng-bind="heading"></h3> </div> <script> var app = angular.module(demoApp, []); app.controller('myCtrl', function($scope) { $scope.heading = "Explaining Data binding!!"; }); </script>
As a result, you can link the data, which is the text “Explaining Data Binding!!” (model part), to an H3 tag (view part).
2. Directives
Directives are intended to be functions that the Angular compiler runs when they are encountered in the DOM to enhance the power of HTML with new syntax. Directives have a name and maybe preset or custom-defined, allowing them to be named anywhere. Its usage is controlled by the preset directive – attribute, comment, element, or class.
Directives in Angular can be put into these categories:
- Component Directive
- Structural Directive
- Attribute directive
3. Dependency Injection
You may think of Dependency Injection in AngularJS as the software design pattern that specifies how software components rely on one another. Factory, value, constant, service, and provider are some of the injectable dependencies in AngularJS.
4. Modules
A module may be considered a container for your app’s many components, such as controllers, services, filters, directives, etc. Most applications contain a main method that creates and connects all the application’s components.
Apps built using AngularJS lack a main method. Instead, modules define declaratively how to bootstrap an application. This strategy has several benefits:
- The declarative approach is simpler to comprehend.
- Code may be put into modules that are reused.
- Because modules delay the execution, they can be loaded in any order (or even concurrently).
- Unit tests are quick since they need to load the necessary modules.
- Modules may be used in end-to-end tests to override configuration.
5. Scope
- In AngularJS framework, the scope plays a vital role. It serves as a bridge between the Controller and the View (HTML).
- Every Angular directive scope object created via a controller or any other directive or service inherits from the parent scope. Each directive has its unique angular scope.
- Accessing variables and methods inside a template or reference function is accomplished using directives within the scope.
- Never will you see a directive create its scope. It needs to be precisely defined.
- Directives use their parent scope by default (the scope from which it is called).
6. Controllers
AngularJS controllers manage the data flow of an AngularJS application. The ng-controller directive is used to define a controller. A controller is a JavaScript object with attributes, properties, and methods. Each controller receives the parameter $scope, which refers to the application or module it is to control.
Setting up an AngularJS Environment
Downloading, Configuring, & Creating an AngularJS Project
To set up an AngularJS development environment, you require the following:
- AngularJS Library
- Editor/IDE
- Browser
- Web server
Go to angularjs.org and click the download option to get the AngularJS library. This will launch the window shown below.
Click the download button in the window after choosing the necessary version from the list.
The AngularJS library may be included via the CDN at the following URL:
https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js
AngularJS is ultimately composed of JavaScript and HTML code. As a result, you are free to install any reputable editor or IDE.
- Sublime Text
- Aptana Studio 3
- Ultra Edit
- Eclipse
- Visual Studio
Web server: Use any locally available web server, such as IIS, Apache, etc., for development purposes.
Browser: Any browser you like may be installed since AngularJS provides cross-browser compatibility. The use of Google Chrome is advised for creating applications, nevertheless.
Illustration
Let’s now create a simple example using the AngularJS framework. Let’s make the HTML file userFirstExample.html, which is seen below.
<!doctype html> <html> <head> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.5.2/angular.min.js"></script> </head> <body ng-app = "browserstackApp"> <div ng-controller = "HelloMyController" > <h2>Welcome {{helloTo.title}} to the world of BrowserStack!</h2> </div> <script> angular.module("browserstackApp", []) .controller("HelloMyController", function($scope) { $scope.helloTo = {}; $scope.helloTo.title = "AngularJS"; }); </script> </body> </html>
To use AngularJS, you add its JavaScript file to the HTML page.
<head> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"> </script> </head>
Next, which section of HTML houses the AngularJS application must be known. This may be accomplished by adding the ng-app property to the AngularJS app’s root HTML element. As seen below, you may either add it to the body element or the html element.
<body ng-app = "browserstackApp"> </body>
View
<div ng-controller = "HelloMyController" > <h2>Welcome {{helloTo.title}} to the world of BrowserStack!</h2> </div>
The ng-controller directive instructs AngularJS on the controller to use with this view. helloTo.title instructs AngularJS to insert the model value helloTo.title in HTML at this location.
Controller
<script> angular.module("browserstackApp", []) .controller("HelloMyController", function($scope) { $scope.helloTo = {}; $scope.helloTo.title = "AngularJS"; }); </script>
This code adds a HelloController controller function to the browserstackApp angular module. Controller functions receive the $scope parameter model. In the helloTo JavaScript object that is added by the controller function, a title field is added.
Execution: Save the above code as userFirstExample.html and launch it in your preferred web browser. You will observe the following result:
Welcome AngularJS to the world of BrowserStack!
What occurs as soon as the page loads in the browser? Let’s find out
- The browser loads an HTML page, which it then analyses.
- The Angular global object is generated after loading the AngularJS JavaScript script.
- It runs the JavaScript that registers controller functions.
- After that, AngularJS searches through the HTML for AngularJS applications and views.
- Once the view has been found, it links it to the relevant controller function.
- After that, AngularJS does the controller operations.
- The data from the model the controller has populated is then used to display the views. The page is now ready.
Components of an AngularJS Application
While it’s true that AngularJS is a robust front-end framework, you won’t be able to take advantage of all of its features until you implement components. An Angular component is a self-contained code that can be reused and updated independently. A basic definition of a component is a method or function that includes both the controller code and HTML tags necessary to create a single UI element.
The final result of your component should be to render the simple piece of HTML:
<span>Hello World!</span>
The syntax for creating a new component is simple. Declare the name of your component and send it along with a config object that details its expected behavior. Here, it will render some very elementary HTML:
angular.module("browserstackApp", []) .component("helloWorld",{ template: 'Hello World!' });
Then, to incorporate that part into our code, you need only…
<div ng-app="browserstackApp"> <hello-world> </hello-world> </div>
Working with AngularJS Directives
In AngularJS, the majority of directives have an ng prefix. ng is short for “angular”. However, ng is not always the required prefix. You may alternatively prefix with x- or data-.
Steps for Adding Directives
- The .directive function is used to generate new directives. You must create an HTML element with the same tag name as the new directive to use it.
- A directive must be named using camel case, such as myNewDirective, but you must use the name separated with – such as my-new-directive.
<body ng-app="browserstackApp"> <my-new-directive></my-new-directive> <script> var app = angular.module("browserstackApp",[]); App.directive("myNewDirective", function(){ return{ template : "<h1>Made by a directive! </h1>" }; }); </script> </body>
You can use different ways to call a directive. That is:
- Element name
- Attribute
- Class
- Comment
It will result in the same result using any of the methods above.
The directive may have certain constraints included. You may limit the use of the directive to certain methods alone. For instance, if a restricted property with the value “C” is added, the directive can only be used by the class.
<script> var app = angular.module("browserstackApp",[]); App.directive("myNewDirective", function(){ return{ restrict : "C" template : "<h1>Made by a directive! </h1>" }; }); </script>
Attributes, element names, comments, and CSS classes are all examples of AngularJS directives. They instruct AngularJS to modify the DOM element and its children or to add a certain behavior to it.
Simply put, a directive tells AngularJS to handle a given element in a certain way. A reusable component may also be built with the help of AngularJS directives.
Controllers in AngularJS
The method for using the ng-controller directive in an angularjs application to define a controller and access data is as follows.
<script type="text/javascript"> var app = angular.module('angularctrlapp', []); app.controller('angularctrl', function ($scope) { $scope.msg = 'Welcome to Browserstack.com'; }); </script> <div ng-app="angularctrlapp" ng-controller="angularctrl"> {{msg}} </div>
If you look at the code above, you’ll see that ng-app serves as the starting point for an angularJS application, and the elements within a div will be able to use angularJS functionality. Check out this Angularjs ng-app directive for additional information about ng-app.
Typically, you use an AngularJS module to create the controller. Because angularjs controllers are called using the $scope object, here you initialized the $scope object in the controller function.
Here is an example of an AngularJS application using a controller:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title> AngularJs Controllers Example </title> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <script type="text/javascript"> var app = angular.module('angularctrlapp', []); app.controller('angularctrl', function ($scope) { $scope.fname = "Welcome to"; $scope.lname = "Browserstack"; }); </script> </head> <body> <div ng-app="angularctrlapp" ng-controller="angularctrl"> First Name: {{fname}}<br /> Last Name: {{lname}}<br /> Full Name: <b>{{fname +" "+ lname}}</b> </div> </body> </html>
The $scope variables fname and lname will get their values from the controller if the example above is executed, and you may display them in the application. The result of using controllers in angularjs applications is as follows:
First Name: welcome to Last Name: Tutlane Full Name: welcome to Tutlane
Services in AngularJS
Services in AngularJS are singletons objects that are instantiated only once per application. Services are used to organize and share code throughout an application. It implies that services might be crucial in carrying out just certain tasks. You may construct model data using $scope and attach it to the views; data manipulation is not its responsibility.
- A few helpful functions are included in service objects and may be called from controllers, directives, filters, etc.
- Numerous built-in services, including $https, $route, $window, $location, etc., are included with AngularJS.
- You may also develop your own service using AngularJS by registering the service.
- The AngularJS compiler may refer to and load a service as a dependency for runtime usage after it has been registered.
There are different approaches to building a service using AngularJS:
Syntax1: Service
var module = angular.module('browserstackApp', []); module.service('customerService', function(){ this.customers = ['Jimi', 'Tom', 'Jake']; });
Syntax2: Factory
var module = angular.module('browserstackApp', []); module.factory('customerService', function(){ var cust = {}; cust.customers = ['Arvind', 'Tom', 'Felix']; return cust; });
Example:
<html> <head> <title>My first AngularJS Service code</title> <Script SRC="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.js"> </Script> <Script> //Defining Services Using Service var app = angular.module('app', []); app.service('MathService', function() { this.add = function(a, b) { return a + b }; this.subtract = function(a, b) { return a - b }; this.multiply = function(a, b) { return a * b }; this.divide = function(a, b) { return a / b }; }); app.service('CalculatorService', function(MathService){ this.square = function(a) { return MathService.multiply(a,a); }; this.cube = function(a) { return MathService.multiply(a, MathService.multiply(a,a)); }; }); app.controller('CalculatorController', function($scope, CalculatorService) { $scope.doSquare = function() { $scope.answer = CalculatorService.square($scope.number); } $scope.doCube = function() { $scope.answer = CalculatorService.cube($scope.number); } }); </Script> </head> <body> <div ng-app="app"> <div ng-controller="CalculatorController"> Enter a number: <input ng-model="number" type="number"> <button ng-click="doSquare()">X<sup>2</sup></button> <button ng-click="doCube()">X<sup>3</sup></button> <div>Answer: {{answer}}</div> </div> </div> </div> </body> </html>
Let’s improve the utility of our component right now. Data is typically loaded by a service and then delivered to the components that need it in a single-page application that consists of many modules.
Here’s how you may put it into practice using a parameter for naming your component:
<div ng-app="myApp"> <hello-world name="'Arvind'" > </hello-world> </div>
By giving your component bindings, you may do this. The name of the attribute that will be added to your component and the kind of binding you will use is essentially defined here. Four distinct kinds of bindings exist:
- = indicates that two-way data binding is being used. In other words, if you update that variable in your component scope, the parent scope will also reflect the change;
- < is for one-way bindings, When you want to read a value from a parent scope and not update it, you use one-way bindings;
- @ is for string parameters;
- If your component needs to output something to its parent scope, use the callback symbol (&)
In your scenario, you should use a simple string so that your component resembles the following:
angular.module("browserstackApp", []) .component("helloWorld",{ template: 'Hello {{$ctrl.name}}!', bindings: { name: '@' } });
The local scope of your component, which is by default connected to a controller named $ctrl, will have bindings added to it. Due to this, the HTML template uses the phrase “$ctrl.name” to get the value to show.
How to test an AngularJS web application on BrowserStack?
It would be best if you had a firm grasp of these core ideas before delving into testing individual components inside an Angular application, and you now do. When doing automated tests in an AngularJS environment, read this AngularJS Testing Guide
To test an AngularJS web application on BrowserStack, follow these steps:
- Choose the browsers and devices to test your AngularJS web application using BrowserStack’s browser matrix.
- For Automated testing, you can either use the BrowserStack Local testing feature or use a Selenium or WebDriver script. If using Selenium or WebDriver script, ensure you have installed the necessary libraries and dependencies, and modify your script to include the BrowserStack credentials.
- Run your tests and review the results to ensure your AngularJS web application works correctly on all browsers and devices.
Closing Notes
One of the main aims of AngularJS from its first release has been to provide a framework for developing unit-testable code. All AngularJS components (controllers, directives, services, and filters) are built using the dependency injector, an elegant and complex component of AngularJS. This makes it possible to easily stub out your code’s dependencies as needed for your tests.
The architectural and testing tools of AngularJS also integrate well with various free and open-source JavaScript build and workflow tools, including Gulp and Grunt. With these tools, you can construct whole new apps from the start, perform your tests flawlessly, and include tools like code coverage and linting into your test execution.
FAQs
1. What is AngularJS used for?
AngularJS offers the ability to convert static HTML into dynamic HTML. This framework extends HTML’s capabilities with built-in attributes and components and facilitates the creation of custom attributes using basic JavaScript.
2. What is the difference between AngularJS and JavaScript?
- Javascript is an object-oriented programming language for applications, particularly for mobile and dynamic online platforms. Its core is the dynamic typing concept.
- AngularJS is an open-source framework that can be used to build dynamic web applications and large single-page web projects. Angular JS is an application development framework based on the MVC architectural paradigm.
3. Is AngularJS a language?
Angular is a framework and platform for creating HTML and TypeScript single-page client applications.
4. Which framework is AngularJS?
AngularJS is a framework built in JavaScript. It can be added using the <script> tag on an HTML page. AngularJS augments HTML attributes with Directives and binds HTML data with Expressions.