如何将控制器绑定到已加载的 html ( Angularjs )
How to bind a controller to loaded html ( Angularjs )
请检查这个Link
我的问题是如何将控制器绑定到 Page2Controller 以在
中打印一些内容
{{wat}}
简单的方法是在控制器中使用$compile
。
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
更好的方法是使用如下答案中的指令:Compiling dynamic HTML strings from database
请检查这个Link
我的问题是如何将控制器绑定到 Page2Controller 以在
中打印一些内容{{wat}}
简单的方法是在控制器中使用$compile
。
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
更好的方法是使用如下答案中的指令:Compiling dynamic HTML strings from database