Thursday, 9 March 2017

How to create and use a Controller ?


A Controller is a JS function to build a model for the view.

var app = angular.module('module1', []);
 
CREATE A CONTROLLER
var myController = function ($scope) {
    $scope.message = "Hello Angular";
}

REGISTER A CONTROLLER WITH THE MODULE

app.controller("controller1", myController);

// Here app is the module name which is already created and controller1 is Controller name



 
You can also Register + Define the controller in one step without defining a variable for controller :
app.controller("controller1", function ($scope) {
        $scope.message = "Hello Angular";
});






 
You can also Define module + Register the controller + Define the controller  :
var app = angular
              .module('module1', [])
              .controller("controller1", function ($scope) {
                    $scope.message = "Hello Angular";
              });


USING CONTROLLER IN VIEW (HTML)
<html ng-app="module1">
<head>
    <script type="text/javascript" src="jquery.min.js"> </script>
    <script type="text/javascript" src="angular.min.js"> </script>

    <link rel="stylesheet" type="text/css" href="bootstrap.min.css">
</head>

<body>
  <div ng-controller="controller1">
      {{ message }}
  </div>
</body>

No comments:

Post a Comment

Note: only a member of this blog may post a comment.