【问题标题】:How we can use the angularjs scope variables in the html which we are appending into the html page via controller?我们如何在通过控制器附加到 html 页面的 html 中使用 angularjs 范围变量?
【发布时间】:2020-02-26 10:40:50
【问题描述】:

我有以下代码

var input = '<div class="form-group">{{variable}}</div>'

我有上面写在控制器内部的代码。我想将此元素推送到视图中,并且我希望从控制器绑定此变量值,但它只是打印与{{variable}} 相同的内容。谁能告诉我该怎么做??

【问题讨论】:

  • 上面的答案是使用$rootScope,但是你可以/应该绑定控制器的范围
  • $scope.data = $sce.trustAsHtml('
    '+$scope.variable+'
    ');并在 Html ng-bind-html="data"
  • 我投票决定保留这个问题,因为建议的副本有不适用的解决方案,会引入安全风险、内存泄漏和其他问题。 - From Review.

标签: javascript html angularjs


【解决方案1】:

ng-bind-html 指令将绑定 html,并将范围变量分配给控制器本身

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $sce) {
    $scope.variable = 'test'
    $scope.firstName = $sce.trustAsHtml("<h1>"+$scope.variable+"</h1>");
    
});
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">

    <div ng-bind-html="firstName"></div>

</body>

【讨论】:

  • 虽然您的解决方案可以工作,但这不是推荐的方法 (IMO) - 例如,如果您将指令绑定到 h1 元素,它将不起作用(这个问题可能不是这种情况,但仍然...)$compile 服务是最好的方法
  • 在控制器中绑定指令有什么意义,如果那是我初始化范围数据的地方..?像 ng-repeat 一样,可以通过在控制器中应用 for 循环来简单地实现。虽然我检查了这个链接 [stackoverflow.com/questions/22370390/… 并发现它很有用。
  • 我没有一个可靠的例子,我同意你的观点。只是 angularjs 有专门为此而设计的服务,这就是我评论的原因。你的回答没有问题:)
  • 我同意@sourav-satyam 的观点,如果代码添加到 HTML 的唯一内容是范围变量,最好使用 ng-bind-html 指令。 AngularJS 团队经过深思熟虑决定不编译控制器中的 AngularJS 指令以及来自ng-bind-html 指令的 HTML。它引入了最好避免的安全风险。
【解决方案2】:

我同意@sourav-satyam 的观点,如果控制器添加到 HTML 中的唯一内容是范围变量,那么最好使用ng-bind-html 指令来完成。 AngularJS 团队慎重决定不编译控制器中的 AngularJS 指令以及来自ng-bind-html 指令的 HTML。它引入了最好避免的安全风险。

我唯一不同的是使用template literal

$scope.firstName = $sce.trustAsHtml(`<h1>${$scope.variable}</h1>`);

演示

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $sce) {
    $scope.variable = 'test'
    $scope.firstName = $sce.trustAsHtml(`<h1>${$scope.variable}</h1>`);        
});
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">

    <div ng-bind-html="firstName"></div>

</body>

【讨论】:

    猜你喜欢
    • 2016-06-05
    • 1970-01-01
    • 2012-01-17
    • 1970-01-01
    • 1970-01-01
    • 2016-12-09
    • 2014-11-15
    • 2015-03-26
    • 1970-01-01
    相关资源
    最近更新 更多