1

please check this Link

here is my question how can I bind a controller to Page2Controller to print some thing in

{{wat}}
4
  • You need to load the html, then use $compile to compile it. Commented May 19, 2016 at 11:57
  • where shall I use it? Commented May 19, 2016 at 12:14
  • Isn't that what directive is for? Commented May 19, 2016 at 12:24
  • I'm new in Angular :) can you clearify it? pls Commented May 19, 2016 at 12:44

1 Answer 1

1

The simple way is to use $compile in the controller.

Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together.

var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope, $http, $sce, $compile) {
  $scope.wat = 'blablalba';
  $http.get("page2.html").then(function (response) {
    var str = '<div ng-controller="Page2Controller"> {{wat}} <div style="background: red; height: 50px; width: 50px"></div> </div>';
    var cont = $compile(response.data)($scope);
    angular.element(document.querySelector('p')).append(cont);
  });
});

app.controller('Page2Controller', function($scope) {

});
<div ng-app="myApp" ng-controller="myCtrl">
  <p></p>
</div>

http://plnkr.co/edit/cOu69mPhfrvaA1buDUjT?p=preview

The better way is to using a directive like in this answer: Compiling dynamic HTML strings from database

Sign up to request clarification or add additional context in comments.

2 Comments

thank you, just a question how can I bind a loaded controller I mean : var str = '<div ng-controller="Page2Controller"> {{wat}} <div style="background: red; height: 50px; width: 50px"></div> </div> app.controller('Page2Controller', function($scope) { });';
I'm not sure I understand the question. I bind a loaded controller? What do you mean by bind?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.