The Angular JS Directives are used to introduce angular features to the already existing html tags. ng-app, and ng-controller are two such Angular JS directives.
Steps to create a Simple Angular JS app
- As the first step, download and install Angular JS if you don't have it already. The link of the website from which it can be downloaded is given below.
When downloading, you can choose the zip version to download.
- Create an html file named index.html. Later, we will add our Angular JS app to this.
- As the next step, let's create the module. The module acts as the container for all angular elements like controllers and directives. Create a js file named app.module, and add the following piece of code.
angular.module('EmployeeApp', []);
- Let's create the controller now. Create a js file named main.controller, and add the following piece of code.
angular.module('EmployeeApp').controller('MainController', ['$scope',
($scope)=>{
$scope.count=0;
$scope.incrementCount=()=>{
return $scope.count++;
}
]);
$scope is used to inject dependencies which controls the view to the controller.
- Next step would be to add the following code inside your head tag in the html file. Make sure that you have the <base href="/app/"> tag in your head tag, placed above the script files mentioned below. And also make sure that you are giving the correct paths to the below mentioned script files.
<script src="angular-1.6.3\angular.js"></script>
<script src="app.module.js"></script>
<script src="main.controller.js"></script>
- Change the body tag using the ng-app directive as shown below.
<body ng-app="EmployeeApp">
- Add the following code to place the div with the controller inside the body tag of the html file.
<div> <h2>Welcome</h2> <div ng-controller="MainController"> <button ng-click="incrementCount()">Increase Count</button> <span>Count: {{count}}</span> </div></div>
As we press the button, the incrementCount function will be called, and the count will be incremented.
- We can test this by building up an ExpressJS server side application, and running on localhost. The page will be loaded, and you will be able to see that when we press the button, the count will be incremented.
No comments:
Post a Comment