AngularJS:更新绑定ng-bind-html

时间:2014-07-16 16:16:02

标签: angularjs

我遇到绑定问题。我使用“ng-bind-html”指令,因为要显示的对象的详细信息文本包含HTML代码。不幸的是,当对象发生变化时,文本不会更新。 'title'和'kurztext'改变了它的值,但是'langtext'(html bound)没有。这是我使用的代码:

<div class="content scrollContainer" ng-model="selectedItem">
    <h2 class="header">{{selectedItem.titel}}</h2>
    <div class="kurztext" ng-show="selectedItem.kurztext">{{selectedItem.kurztext}}</div>
    <div class="langtext" ng-bind-html="selectedItem.langtext"></div>
</div>

在Javascript中,我只是从数组中选择一个对象并将其分配给$ scope.selectedItem来更改显示的项目。这是我的JS代码(不应该与问题相关):

var items;

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

app.controller("MainCtrl", function ($scope, $sce){
    $scope.items = items;
    $scope.selectedItem = $scope.items[0];

    $scope.showItem = function(item){ // called on click on list item
        $scope.selectedItem = item;
    }

    $scope.openItemLink = function(id){
        for (var i=0; i<$scope.items.length; i++){
            if ($scope.items[i].uid==id){
                $scope.showItem($scope.items[i]);
                break;
            }
        }
    }

    $scope.getLink = function(id){
        var it = 0;
        for (var i=0; i<$scope.items.length; i++){
            if ($scope.items[i].uid==id){
                it = $scope.items[i];
                return it.titel;
            }
        }
        return "----";
    }
});

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

你需要清理它,添加angular-sanitize.js并在你的模块中

var App = angular.module('process', ['ngSanitize']);
控制器中的

App.controller(
    'Init',
    [
        '$scope', '$sce',
        function($scope, $sce)

和你的代码

$scope.details = $sce.parseAsHtml($scope.details);

我知道如果我不这样做它也不起作用,

根据文件

By default, the innerHTML-ed content will be sanitized using the $sanitize service.
 To utilize this functionality, ensure that $sanitize is available,
 for example, by         including ngSanitize in your module's dependencies (not in core  Angular.)
 You may also bypass sanitization for values you know are safe.
 To do so, bind to an explicitly trusted value via $sce.trustAsHtml.
 See the example under Strict Contextual Escaping (SCE).