Controllers

Controllers are defined by JavaScript code and are used to augment the AngularJS scope. It's effectively a way to control the data that is flown between the view (HTML) and the code within the web application. Controllers are used to generally achieve two things:

  • Set up the initial state of the $scope object and the view
  • Add behavior to the $scope object

It should not be used for any presentation logic and mainly contains the business logic of an app. It should also not be used to filter an output, format the input, or to share code between different controllers. The controller can be loaded within a segment of the UI by using the attribute ng-controller as in the following example:

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body ng-app="MasteringQS">
<div ng-controller="myCtrl">
<h1>My name is {{name}}</h1>
</div>
<script>
angular.module('MasteringQS', [])
.controller('myCtrl', ['$scope', function($scope) {
$scope.name = "Martin Mahler";
}]);
</script>
</body>
</html>

While large web applications can have multiple contextually separate controllers, it's generally common to have few controllers.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.165.144