Skip to content Skip to sidebar Skip to footer

How To Bind An Angularjs Controller To Dynamically Added Html?

For this scenario, I have a page of HTML with some AngularJS directives, controllers, etc. Something like this:

Solution 1:

I've faced the same issue, here's what I came up with :

<divid="mController"ng-controller="mainController"></div><divid="ee">
  2nd controller's view should be rendred here
</div>

and calling setCnt() function will inject and compile the html, and it will be linked to the 2nd controller:

var app = angular.module('app', []);

functionsetCnt() {
  // Injecting the view's htmlvar e1 = angular.element(document.getElementById("ee"));
  e1.html('<div ng-controller="ctl2">my name: {{name}}</div>');
  
  // Compile controller 2 htmlvar mController = angular.element(document.getElementById("mController"));
  mController.scope().activateView(e1);
}

app.controller("mainController", function($scope, $compile) {
  $scope.name = "this is name 1";

  $scope.activateView = function(ele) {
    $compile(ele.contents())($scope);
    $scope.$apply();
  };
});

app.controller("ctl2", function($scope) {
  $scope.name = "this is name 2";
});

here's an example to test this : https://snippet.run/x4bc

hope this helps.

Solution 2:

Lets take a small template

var  template = '<div ng-controller = "someController">';
      template += '<All html you want to add>'; 
      template += '</div>';

Now if you want to add this template you have to do the following two things:

1) Instantiate your controller by $controller

2) Compile your template.

//this creates a new scopevar$scope = $rootScope.$new();  
//Controller initialize with $scope$controller('someController',{$scope,$scope});   
var templateEl = angular.element(template);
//Now compile the template with scope $scope$compile(templateEl)($scope);
angular.element('body').append(templateEL);

Solution 3:

You might want to use $compile service. That's what angular do at first place.

And also this guide: http://docs.angularjs.org/guide/compiler

Solution 4:

I had the same problem. This worked for me: https://docs.angularjs.org/api/ng/function/angular.injector

Solution 5:

I think ng-include might help you, it loads a partial page into the element and compiles and processes it like any other part of your web page.

If This element is the main view of your web app, and you want to load different 'screens' into it, depending on the url, ng-view may come in handy.

Post a Comment for "How To Bind An Angularjs Controller To Dynamically Added Html?"