3

I have a little problem using AngularJS. I've implemented a dynamic route which loads a main controller "PagesController" and this controller loads respective views based on url info. Nice!

But know I want to compile views and assign a controller without needing "ng-controller". Because I don't want assign a view to a single controller.

My dynamic route:

app.config( ['$routeProvider', 
    function( $routeProvider ) {
        $routeProvider
            .when( '/:pagename', { template: 'blank', controller: 'PagesController' })
    }
]);

My Main Controller:

app.controller( 'PagesController', [ '$scope', '$routeParams', '$compile', '$scope',
    function( $scope, $routeParams, $compile, http, $controller, $rootScope ) {

        $http.get( 'app/pth/' + $routeParams.pagename ).then( function ( view ) {

            $( '#views' ).html( $compile( view.data )( $scope ) );
        });

    }] 
);

A regular controller:

app.controller( 'TestCtr', [function() {

}]);

My view:

<div ng-controller="TestCtr" >
    <h2>Welcome!</h2>
</div>

What I whant (same view without ng-controller):

<div>
    <h2>Welcome!</h2>
</div>

This a simple example but basically what I want is in near future to use the view above in several controllers contexts. Thank you!

Miguel Q.
  • 567
  • 4
  • 14
  • 1
    You want to use multiple controllers with one template? Why not to use `ng-include`? – akn May 26 '14 at 18:49

1 Answers1

1

Either bind ng-controller to a scope variable or use ng-include. Note that controllers that are dynamic need a $destroy handler (I don't know much about it so I ll just leave this reference (What is the lifecycle of an AngularJS Controller?).

Community
  • 1
  • 1
Alex C
  • 1,334
  • 2
  • 18
  • 41