Angularjs ng controller directive

The ng-controller directive in AngularJS is used to attach a controller to a view element. Controllers are used to define the behavior of a view and to handle user interactions. The ng-controller directive allows you to associate a controller with a specific part of a view.

Here is an example of using ng-controller with a div element:

ref‮igi:ot re‬ftidea.com
<div ng-controller="MyController">
  # {{ title }}
  <p>{{ message }}</p>
</div>

In this example, the ng-controller directive is used to attach a controller called MyController to a div element. The div element contains some AngularJS expressions that are bound to scope variables defined in the controller. The {{ title }} expression is bound to a scope variable called title, and the {{ message }} expression is bound to a scope variable called message.

Here is an example of defining a controller using the controller method:

angular.module('myApp', [])
  .controller('MyController', function($scope) {
    $scope.title = 'Hello, world!';
    $scope.message = 'This is a message from the controller.';
  });

In this example, a module called myApp is created using the angular.module method. The controller method is used to define a controller called MyController, which takes a scope object as an argument. The scope object is used to define the title and message variables, which are bound to the expressions in the view.

You can also use the controller as syntax to attach a controller to a view element. Here is an example:

<div ng-controller="MyController as ctrl">
  # {{ ctrl.title }}
  <p>{{ ctrl.message }}</p>
</div>

In this example, the ng-controller directive is used to attach a controller called MyController to a div element using the controller as syntax. The controller is referred to as ctrl in the view, and the scope variables are accessed using the ctrl. prefix.

Using the ng-controller directive, you can define the behavior of a view and handle user interactions by defining a controller and binding scope variables to expressions in the view.