0

Can you help me please? I want to set controller name which contains in scope of another controller.

JS file:

.controller('PageCtrl', [
  '$http',
  '$scope',
  '$routeParams',
  '$location',
  function($http, $scope, $routeParams, $location){

    switch($routeParams.page) {
      case 'companies':
        $scope.CurrentPageCtrl = 'CompaniesCtrl';
      break;
      default:

      break;
    }

  }])

.directive('myPagecontent', function() {
  return {
    template: '<ng-controller ng-controller = "{{CurrentPageCtrl}}"></ng-controller>'
  };
})

HTML file:

<ng-controller ng-controller = "PageCtrl">
    <my-pagecontent></my-pagecontent>
</ng-controller>

And I get error:

angular.js:13642 Error: [ng:areq] Argument '{{CurrentPageCtrl}}' is not a function, got undefined
John V
  • 875
  • 6
  • 12

1 Answers1

0

This can be a bit tricky since ng-controller in this case expects an expression that evaluates to a controller constructor function, not to a string that contains the controller name.

One way to solve it is by doing the following:

app.controller('PageCtrl', [
  '$http',
  '$scope',
  '$location',
  function($http, $scope, $location) {

    $scope.CurrentPageCtrl = Controller1;
  }
]);

function Controller1($scope) {

  console.log('Controller1');
}

app.controller('Controller1', Controller1);

function Controller2($scope) {

  console.log('Controller2');
}

app.controller('Controller2', Controller2);

app.directive('myPagecontent', function() {
  return {
    template: '<ng-controller ng-controller="CurrentPageCtrl"></ng-controller>'
  };
});

Demo: http://plnkr.co/edit/s3yy2fdF5OgBjPcKWikw?p=preview

An alternative solution is to create a directive that runs before everything else, that takes a variable with the controller name, adds ng-controller with the correct value and then remove itselves.

tasseKATT
  • 38,470
  • 8
  • 84
  • 65