html - 如何从 AngularJS 函数返回 html?

标签 html angularjs function controller

我是全新的 AngularJS 样式代码创建者。我正在尝试以 AngularJS 格式重新创建现有网站。

我终于想出了如何在外部文件中制作应用程序/ Controller 并为 Controller 提供功能。然后我可以让这些函数返回变量,特别是字符串,以填充我的 .html 文件中的信息,但是当我使用 html 标签时,它们在 .html 中用作文字。

我正在尝试找出如何以类似的方式填充我的 html 模板,但 html 可以正常工作。

在其他 JS 格式中,我可以写入文档/响应,或者至少让函数返回一个值,然后让原始 JS/HTML 将该返回值写入 html。

我在页脚中尝试类似的操作,但 Footer() 有一个字符串需要显示在两行上。

要遵循的示例代码(我将把它编辑到重要的部分): HTML:

<!DOCTYPE html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
        <script language="JavaScript" src="./Universal.js" runat="server"></script>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <link href="./Main.css" rel="stylesheet" type="text/css">
    </head>
    <body id="idBody" ng-app="Universal">
        <table id="idTableMain">
            <tr id="idFooterRow">
                <td id="idFooterMain" colspan="3">
                    <p id="idFooterContent" ng-controller="UniversalController">
                        {{Footer()}}
                    </p>
                    <p id="idFooterManagement" ng-controller="UniversalController">
                        {{WebMaster()}}
                    </p>
                </td>
            </tr>
        </table>
    </body>
</html>

应用/ Controller :

var Universal = angular.module("Universal", []);

Universal.controller("UniversalController", ['$scope', function ($scope)
    {
        $scope.Footer = function()
        {
            $scope.vResult = "© Copyright 2012 All rights reserved<br>";    
            $scope.vResult += "House That Kamurai Built";
            return $scope.vResult;
        };

        $scope.WebMaster = function()
        {
            $scope.vResult = "Website managed by Kamurai.";
            return $scope.vResult;
        };
    }]);

最佳答案

使用 ng-bind-html 在页面上显示 HTML,但在此之前,您应该通过调用 $sce.trustAsHtml< 使 html 可信 方法。

$scope.Footer = function() {
    $scope.vResult = "© Copyright 2012 All rights reserved<br>";
    $scope.vResult += "House That Kamurai Built";
    return $sce.trustAsHtml($scope.vResult);
};

HTML

<p id="idFooterContent" 
  ng-controller="UniversalController" 
  ng-bind-html="Footer()">
</p>

Demo

Suggestion: You could have placed ng-controller="UniversalController" directly on table instead of placing twice on page. I don't know what special case you had, that led you there.

关于html - 如何从 AngularJS 函数返回 html?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46101103/

相关文章:

html - 显示动画 GIF 图像后 Internet Explorer CPU 使用率升高

javascript - 在scrollTop上应用Jquery效果时遇到问题

javascript - 我写的这个函数有什么问题吗?

python - 为什么我的 Python 函数不执行?

php - proc_open 被禁用。但不在 php.ini 中

python - 使用函数 1 的输出作为函数 2 的输入

javascript - 更改段落 jQuery 中的内部值

javascript - 代码中硬编码的 Web API 调用与多种环境的比较

javascript - 无法创建可重用的函数来取消选中 AngularJS 中的单选按钮

javascript - 使用 $emit 刷新父数据时,AngularJS 子 Controller 数据未加载到 UI 上