Sometimes we may be required to display a list of items in the view, so the question is that how can we display a list of items defined in our controller onto our view page.
Angular provides a directive called "ng-repeat" which can be used to display repeating values defined in our controller.
Let's look at an example of how we can achieve this.
<!DOCTYPE html> <html> <head> <meta chrset="UTF 8"> <title>Event Registration</title> <link rel="stylesheet" href="css/bootstrap.css"/> </head> <body > <h1> Guru99 Global Event</h1> <script src="https://code.angularjs.org/1.6.9/angular.js"></script> <div ng-app="DemoApp" ng-controller="DemoController"> <h1>Topics</h1> <ul><li ng-repeat="tpname in TopicNames"> {{tpname.name}} </li></ul> </div> <script> var app = angular.module('DemoApp',[]); app.controller('DemoController', function($scope){ $scope.TopicNames =[ {name: "What controller do from Angular's perspective"}, {name: "Controller Methods"}, {name: "Building a basic controller"}]; }); </script> </body> </html>
Code Explanation:
If the code is executed successfully, the following Output will be shown when you run your code in the browser. You will see all items of the array (Basically the TopicNames in topics) displayed.
Output:
An advanced controller example would be the concept of having multiple controllers in an angular JS application.
You might want to define multiple controllers to separate different business logic functions. Earlier we mentioned about having different methods in a controller in which one method had separate functionality for addition and subtraction of numbers. Well, you can have multiple controllers to have a more advanced separation of logic. For example, you can have one controller which does just operations on numbers and the other which does operations on strings.
Let's look at an example of how we can define multiple controllers in an angular.JS application.
<!DOCTYPE html> <html> <head> <meta chrset="UTF 8"> <title>Event Registration</title> <link rel="stylesheet" href="css/bootstrap.css"/> </head> <body > <h1> Guru99 Global Event</h1> <script src="https://code.angularjs.org/1.6.9/angular.js"></script> <div ng-app="DemoApp"> <div ng-controller="firstcontroller"> <div ng-controller="secondcontroller"> {{lname}} </div> </div> </div> <script> var app = angular.module('DemoApp',[]); app.controller('firstcontroller', function($scope){ $scope.pname="firstcontroller"; }); app.controller('secondcontroller', function($scope){ $scope.lname="secondcontroller"; }); </script> </body> </html>
Code Explanation:
If the code is executed successfully, the following Output will be shown when you run your code in the browser. You will see all text of "secondController" as expected.
Output:
Summary