Search code examples
angularjsangularjs-directiveangularjs-ng-repeatangular-controller

Angular, how to assign controller to markup before ng-repeat


Can anyone tell me if is possible to assign a controller from a directive to the markup before ng-repeat does his thing?

The code below is just an example of what i want to do

<body ng-app="App">
<div my-t>
  <div ng-repeat="obj in List">
    {{obj.Name}}
  </div>
</div>

angular.module('App',[])
.directive('myT',[function(){
    return {
        replace : true,
        transclude : true,
        template : '<div ng-controller="listCtrl"><div ng-transclude></div></div>'
    };
}])
.controller('listCtrl', ['$scope', function($scope){
    $scope.List = [
        {Name: 'a'},{Name: 'b'}
    ];
}]);

Plunker

The problem is that when my directive changes the template, assigning the ng-controller the ng-repeat has already compiled and so it will display no data. Moving the ng-controller to the markup it´s not an option.

Best.


Solution

  • You can also put the controller to your directive, with controller: 'listCtrl', you can then also remove the ng-controller from your template.