Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would you put a controller in a directive with AngularJS?

Tags:

angularjs

I recently saw this example. It's the first time I have seen a controller inside a directive. Is this a normal thing to do. I thought you were supposed to keep these two in different areas for testability:

myModule.directive('myComponent', function(mySharedService) {
    return {
        restrict: 'E',
        controller: function($scope, $attrs, mySharedService) {
            $scope.$on('handleBroadcast', function() {
                $scope.message = 'Directive: ' + mySharedService.message;
            });
        },
        replace: true,
        template: '<input>'
    };
})
like image 714
Alan2 Avatar asked Apr 06 '13 10:04

Alan2


People also ask

Why are controllers used in AngularJS?

AngularJS controllers are used to control the flow of data of AngularJS application. A controller is defined using ng-controller directive. A controller is a JavaScript object containing attributes/properties and functions.

What is difference between controller and directive AngularJS?

A controller is usually used to contain and maintain the logic for your view, which gets bound to your view via $scope. A directive is something that you might use repeatedly and is called in your view directly through the directive name which you can pass in as an attribute.

What is meant by controller in AngularJS?

In AngularJS, a Controller is defined by a JavaScript constructor function that is used to augment the AngularJS Scope. Controllers can be attached to the DOM in different ways.

What is directive controller?

Definition and Usage The ng-controller directive adds a controller to your application. In the controller you can write code, and make functions and variables, which will be parts of an object, available inside the current HTML element. In AngularJS this object is called a scope.


1 Answers

Generally, you'd use controllers in directives to be able to share them between directives, on an element. It allows for directives to comunicate between them easily.

See here for a great explanation of how this works: http://egghead.io/video/angularjs-directive-to-directive-communication/

like image 53
Tiago Roldão Avatar answered Oct 05 '22 06:10

Tiago Roldão