Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign controller to view dynamically

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!

like image 897
Miguel Q. Avatar asked Apr 15 '26 08:04

Miguel Q.


1 Answers

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?).

like image 173
Alex C Avatar answered Apr 16 '26 21:04

Alex C



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!