Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-controller inside a angularjs directive?

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?

like image 855
JeffLL Avatar asked Mar 02 '26 17:03

JeffLL


1 Answers

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>'
  }
}
like image 126
rob Avatar answered Mar 06 '26 01:03

rob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!