Monojit Sarkar
Monojit Sarkar

Reputation: 2451

When one should declare controller inside directives

i am new in angular and that why i do not know the scenario like when one should declare controller inside directives.

see one sample code

<body ng-app="App">
    <div ng-controller="AppCtrl">
        <div data-items></div>
    </div>
</body>

angular.module('App', []).
// sample data
controller('AppCtrl', function($scope){
    $scope.items =[
        {'title': 'Item 3'},
        {'title': 'Item 2'},
        {'title': 'Item 1'}
    ]
}).
directive('items', function(){
    return {
        template: '<span ng-repeat="item in items">{{item.title}}</span>'+
        '<h1>{{currentItem}}</h1>',
        controller: function($scope, orderByFilter){  
            $scope.items = orderByFilter($scope.items, 'title',false);
            $scope.currentItem = $scope.items[0].title;
        }
    }
})

in the above code there is one directive called items and there must notice one controller too. just tell me in easy way when we have to declare controller inside directive?

what kind of purpose controller inside directive solve ? please me to understand the significant of declaring controller inside directive. thanks

Upvotes: 0

Views: 249

Answers (2)

Mazhar Ul Hassan
Mazhar Ul Hassan

Reputation: 56

There can be multiple scenarios when you need to add controller inside a directive but there are no hard and fast rule for it. First thing is when your directive has an isolated scope then you need to write a controller inside a directive.

Also when you have an extended functionality required to be written for your template then you need to write controller inside a directive. You can also pass reference to the controller in your directive.

using controller: 'controllerName',

Upvotes: 1

Thalaivar
Thalaivar

Reputation: 23622

in the above code there is one directive called items and there must notice one controller too. just tell me in easy way when we have to declare controller inside directive?

You need a controller inside directive, when you want your child directive to access the parent directives controller. There is a require attribute used in directive which would require the directive's controller.

Controller for a directive is defined in one's context, it can be injected in other directive for a inter-directive communication.

In the below example, i am trying to call ngModel directive's controller.

myApp.directive('myDirective', function(){
  return {
    require: 'ngModel',    
  }
});

Upvotes: 0

Related Questions