【问题标题】:ngSanitize is not working using angularJs?ngSanitize 不能使用 angularJs 工作?
【发布时间】:2017-02-06 14:59:21
【问题描述】:

我有模态窗口,其中有来自父控制器的数据我也有模态搜索功能,但是当我打开模态时,它不会将数据呈现到模态视图中,我在控制台中看到对象打印,但它没有绑定到 html。 我在下面粘贴了错误,知道这里实现了什么错误吗?

searchModal.html

<div class="row search-input-margin">
    <div class="col-md-12 form-group">
        <div class="col-md-3">
            <label for="search">Search Logs:</label>
        </div>
        <div class="col-md-9">
            <input type="text" class="form-control" id="search" ng-model="vm.searchLog">
        </div>
    </div>
</div>
<div class="modal-body">
    <div class="row">
        <ul class="searchLogsText">
         <li  ng-repeat="item in data  | filter:vm.searchLog track by $index" ng-bind-html="item | highlight:vm.searchLog"></li>
        </ul>
    </div>
</div>

searcCtrl.js

angular.module('loggingApp').controller('SearchController',function ($scope,$rootScope,$uibModalInstance,searchFactory) {
    'use strict';
    $scope.cancel = function() {
        $uibModalInstance.close();
    }
    $scope.vm ={
        searchLog:'',
        searchLength:0,
        searchResults: []

    };
    $scope.data = angular.copy(searchFactory.getDitLogs());
    console.log(searchFactory.getDitLogs());
});

错误:

错误:[$sce:itype] 试图信任需要字符串的内容中的非字符串值:上下文:html

【问题讨论】:

  • 看起来您的 item 不是字符串 (/html),而是一个对象。所以你的searchFactory.getDitLogs() 可能会返回一个对象数组。也许你的意思是ng-bind-html="item.someHtmlProperty"
  • “searchFactory.getDitLogs”函数的代码会有所帮助,创建一个简单的示例来说明该函数返回什么?
  • 它只是 getter 和 setter 工厂,所以我从父级设置数据并进入模态。控制台正在打印数据
  • 看起来您没有将 ngSanitize 添加为依赖项... angular.module('loggingApp', ['ngSanitize']) ...
  • ngSanitize 添加了我没有添加 app.js 来质疑,但它的依赖是存在的

标签: javascript angularjs twitter-bootstrap


【解决方案1】:

您需要添加 ngSanitize 作为依赖项,您应该调用 $sce.trustAsHtml 函数;当您想将字符串用作 html 时。

  var myApp = angular.module('myApp',['ngSanitize']);

  myApp.controller('myCtrl', ['$sce', '$scope' , function($sce, $scope) {
      var html = '<div>Hello Html!</div>'; 
      $scope.editorHtml = $sce.trustAsHtml(html);

    }]);

查看此jsfiddle 或查看我的 aswser here 了解更多详情

【讨论】:

  • 不需要$sce依赖,也不需要使用trustAsHtml
  • 我该怎么做?你能用my js fiddle sample 做到这一点吗?
  • “是”是什么意思!我的脚本不再起作用了!!!运行两个示例以查看不同的结果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-19
  • 1970-01-01
  • 1970-01-01
  • 2015-08-09
  • 2018-03-21
相关资源
最近更新 更多