3

In many tutorials, I've seen controllers being passed into a directive like this:

.directive("mainRightPanel", function(){
  return {
        templateUrl: "views/partials/panels/mainRightPanel.html",
        controller: function($http, $filter, $scope) {
            var info = this;
            $scope.authorWorks;
            $http.get('test/book_data.json').success(function(data){
                $scope.authorWorks= data;
            });
          },
}

However, I'd like to do it differently. Instead of writing javascript like the above, I'm having problems calling a controller from within the directive, like this

<div ng-app="mainLeftPanelModule" ng-controller="leftPanelController" class="list-group ">

Is this possible? And if it is, is there anything wrong with attaching a controller this way?

4
  • Controllers in directives are "auto-call" with jus the use of the directive you do not need to use ngController Commented May 26, 2014 at 0:06
  • @Dalorzo thank you, but I'm trying to see if I can call the controller from within the directive, and NOT have to link the controller from the directive definition! Commented May 26, 2014 at 0:09
  • you can use ng-controller anywhere. Even inside a directive template. Are you having troubles with that? Commented May 26, 2014 at 4:20
  • @rob you're right! I think I made a mistake by having ng-app and ng-controller on the same div. If you answer my question, I'll be sure to mark it as the correct one, thanks! Commented May 26, 2014 at 21:58

1 Answer 1

5

You can put an ng-controller anywhere inside your ng-app including inside a directive template. for example this should work:

.directive("mainRightPanel", function(){
    return {
    template: '<div ng-controller="myCtrl">The rest of your directive can go here<div>'
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.