Dynamically Loading Controllers in angularjs

Dynamically Loading Controllers in angularjs

Simple AngularJS provides a simple easy way to associate a angularjs view with a controller all the angular and load everything at runtime call this url using the $routeProvider object.for Dynamically Loading Controllers in angularjs

The AngularJS providers simple exits that are injected into config() file all the settings are used to dynamically url load to register controllers, and register directives, filters and more directives after a given script is angularjs dynamically loaded. Notice that within the (settings) config() function an object literal each is assigned to angular app.register module (app represents the web-application’s module)

Also Read :   jQuery Ajax Live Data Searching System in PHP





$routeProvider
     .when('/product',
        {
            controller: 'productController',
            templateUrl: '/app/views/product.html'
        })
    .when('/customerorders/:customerID',
        {
            controller: 'productOrdersController',
            templateUrl: '/app/views/customerOrders.html'
        })
    .when('/orders',
        {
            controller: 'OrdersController',
            templateUrl: '/app/views/orders.html'
        })
    .otherwise({ redirectTo: '/product' });

We can all the one load controller dynamically load by resolve each attribute of $routeProvider used in .when function.

var my4App = angular.module ('hw',['ngRoute','ngResource']);
my4App.config(['$routeProvider', '$controllerProvider', function($routeProvider, $controllerProvider) {
my4App.regCtrl = $controllerProvider.register;
 
//function call loadcontroller
function loadcontroller(controllerSubPath){
$.ajaxSetup({async:false});
$.getScript("scripts/controllers/" + controllerSubPath + ".js").done(function( script, textStatus ) {
}).fail(function( jqxhr, settings, exception ) {
console.log( exception );
});
}
 
/* router provider */
$routeProvider
.when('/Rights',{templateUrl:'views/Right/datasearch.html', controller:'searchCtrl', resolve: { load: function () {loadcontroller("right/searchCtrl");}}})
.otherwise({
redirectTo: '/'
});
}])




set the dynamic controller for directives

HTML Markup code

<div add-icons controller-name="FirstCtrl">
</div>
<div add-icons controller-name="SecondCtrl">
</div>

Angular script code

angular.module('myApp',[]).

directive('addIcons', function(){
return {
    restrict : 'A',
    scope:{},
    controller : "@",
    name:"controllerName",    
    template:'<input type="button" value="(+) plus" ng-click="add()">'
  }
}).
controller("FirstCtrl",function($scope){
     $scope.add = function(){
        alert("IconsOne add ");
      }
}).
controller("SecondCtrl",function($scope){
     $scope.add = function(){
        alert("IconsTwo add ");
      }
});

Demo

   

Add a Comment

Your email address will not be published.