[英]How get text with HTML tags from server and display it in client side with HTML markup? (using php and angularjs)
I'm trying to learn web development by creating an app. 我正在尝试通过创建一个应用程序来学习Web开发。 I'm using Angularjs in client side and php on server side.
我在客户端使用Angularjs,在服务器端使用php。 I need to load content of articles from server when a user select an article.
用户选择文章时,我需要从服务器加载文章的内容。 I want do the html markup in the server side and then get the text in client side and display it.
我想在服务器端进行html标记,然后在客户端获取文本并显示它。 (ie I want to do save text as "< h1>Heading< /h1> < p>paragraph< /p>" and then transfer the text to client and display it in client.
(即,我想将文本另存为“ <h1>标题</ h1> <p>段落</ p>”,然后将文本传输到客户端并在客户端中显示。
I tried echoing the text in a php file with markup tags and then get the text through $http service in angularjs. 我尝试用标记标签在php文件中回显文本,然后通过angularjs中的$ http服务获取文本。 But the browser does not seem to identify the markup tags but display the html tags with the text.
但是浏览器似乎无法识别标记标签,而是显示带有文本的html标签。
How can I achieve this? 我该如何实现?
notes2.php notes2.php
<?php
$variable = <<<XYZ
<html>
<body>
<h1>Heading</h1>
<p> paragraph </p>
</body>
</html>
XYZ;
echo $variable;
?>
getnotes.html getnotes.html
<!DOCTYPE html>
<html>
<script src="js/angular.min.js"></script>
<script src="js/angular-route.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
<p id="demo"></p>
<script>
var app = angular.module("myApp", ["ngRoute"]);
app.controller('myCtrl', ['$scope', '$http', function($scope, $http){
$http.get("http://localhost:8080/json_test/notes2.php").then(function(response) {
$scope.myText = response.data;
});
}]);
</script>
<script>
document.getElementById("demo").innerHTML = "{{myText}}";
</script>
</body>
</html>
You can use ng-bind-html
to bind the string as HTML if you dont have any angular binding in it in angular app. 如果您在angular应用程序中没有任何角度绑定,则可以使用
ng-bind-html
将字符串绑定为HTML。 Like this: 像这样:
// in controller
$scope.html = "< h1>Heading< /h1> < p>paragraph< /p>";
// in HTML
<div ng-bind-html="html"></div>
If you have any angular binding you can use $compile
service for binding it. 如果有任何角度绑定,则可以使用
$compile
服务进行绑定。 $compile
creates DOM elements with angular binding to scope. $compile
创建与范围成角度绑定的DOM元素。 That's what you would normally use to render your DOM to have two-way binding etc. working. 那就是您通常用来使DOM具有双向绑定等功能的方式。 In most cases you don't call it manually because if you add
template
or templateUrl
to the direcive definition object it will run $compile
automatically. 在大多数情况下,您无需手动调用它,因为如果将
template
或templateUrl
添加到直接定义对象中,它将自动运行$compile
。
Why don't you write like this inside controller's scope, <script> document.getElementById("demo").innerHTML = $scope.myText; </script>
为什么不在控制器的作用域内像这样写
<script> document.getElementById("demo").innerHTML = $scope.myText; </script>
<script> document.getElementById("demo").innerHTML = $scope.myText; </script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.