sday
sday

Reputation: 1051

How to use angular injection with a dynamically loaded controller

How do I get a dynamically loaded template and controller injected? After loading my .html partial and .js controller, I would assume the next step is $injector? But how do I use it? something like this...?

My progress so far: http://plnkr.co/edit/rB5zteYTZ2L1WB5RzlHg

data is returned from a $http.get()

var $injector = angular.injector(['ng']);

$injector.invoke(function($rootScope, $compile, $document) {
    $compile(data)($rootScope);
    $rootScope.$digest();
});

What format does the Controller.js file need to be in for the injector/compiler to wire it up correctly? Can I simply do what I did in Plunker?

Controller1.js

app.controller('Controller1', function ($scope, $famous) {
      console.log("Inside Controller1");
});

Note: I am specifically trying to avoid using requirejs, ng-route, ui-route, ocLazyLoad, etc. I would like to understand the very basics of what these packages accomplish for routing and dynamic loading of a view/controller.

Upvotes: 0

Views: 248

Answers (1)

timtos
timtos

Reputation: 2305

I am not sure if I totally understand your question but it looks like you want to load views and controllers dynamically. I am using a combination of angular ui router and angularAMD. It works very smoothly and with that approach you get a nice separation and on-demand loading.

From angular ui router webpage:

templateUrl: "partials/state1.list.html",
   controller: function($scope) {
   $scope.items = ["A", "List", "Of", "Items"];
}

With that configuration the specified controller will get loaded and connected to the state1.list.html.

Does that help?

Upvotes: 0

Related Questions