0

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

Monojit Sarkar
  • 2,353
  • 8
  • 43
  • 94

2 Answers2

1

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',

  • if u see my posted then must notice there is no isolated scope in my directive but there is controller. better discuss the significance of controller inside directive with sample code for better clarity. – Monojit Sarkar Apr 21 '16 at 13:01
0

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',    
  }
});
Thalaivar
  • 23,282
  • 5
  • 60
  • 71