【问题标题】:Change ng-bind-html value using controller使用控制器更改 ng-bind-html 值
【发布时间】:2016-04-10 12:16:58
【问题描述】:

我想更改 ng-bind-html 值,但不知道该怎么做。

我最初的 ng-bind-html 值是:-

<p class="forum-content" id="{{post.id}}" ng-bind-html="renderHtml(post.content)|truncate:90"></p>

并且想要这个值:

&lt;p class="forum-content" id="{{post.id}}" ng-bind-html="renderHtml(post.content)"&gt;&lt;/p&gt;

按下按钮后。

最初它将我的数据截断为 90 个字符,我想在按下按钮后显示完整数据。我的主要功能是在按下按钮(阅读更多)后显示完整数据。

【问题讨论】:

  • 您是否尝试直接在renderHtml 函数中执行truncate 部分?然后你的按钮只是更新作用域中的一个布尔值,并基于该布尔值,renderHtml 是否返回截断值。
  • 我试过了,但是没用。
  • $scope.renderHtml = function (html_code) { return $sce.trustAsHtml(html_code); };这是我的renderHtml。你能建议我这样做的方法吗?

标签: angularjs ionic-framework ng-bind-html


【解决方案1】:

简单的技巧:

<p class="forum-content" id="{{post.id}}" ng-bind-html="renderHtml(post.content)|truncate:limit"></p>

<button ng-click="showAll()">Show all</button>

在控制器中:

$scope.limit = 90;
$scope.showAll = function() {
    $scope.limit = 100000000; // should be large enough not to truncate anything
};

这仍然会尝试截断。如果你真的想避免它,一个更干净的解决方案是使用控制器中的过滤器:

<p class="forum-content" id="{{post.id}}" ng-bind-html="renderAndTruncateHtml(post.content)"></p>

<button ng-click="showAll()">Show all</button>

在控制器中:

$scope.shouldTruncate = true;
$scope.renderAndTruncateHtml = function(value) {
    var result = $scope.renderHtml(value);
    if ($scope.shouldTruncate) {
        result = $filter('truncate')(result, 90);
    }
    return result;
};
$scope.showAll = function() {
    $scope.shouldTruncate = false;
};

【讨论】:

  • 我还想问一件事。我只想显示特定帖子的全部内容。您的解决方案显示所有帖子的全部内容。
  • 将 shouldTruncate 标志(或第一个解决方案中的限制)存储在帖子本身中,以便每个帖子都有自己的标志/限制。
  • post 包含一个 json 数据,使用 API 获取。
  • 这不会改变任何事情。在获取它们时添加此标志,或者使用shouldShowAll 标志而不是shouldTruncate,因此如果该标志不存在,则它是虚假的,并且默认情况下将截断帖子。
  • 你能告诉我如何在获取的数据中添加一个标志吗?
【解决方案2】:

试试这样的。

控制器:

var truncateText = true;

$scope.renderHtml = function(content){
  // your code here
  return truncateText ? $filter('truncate')(content, 90) : content;
};

$scope.toggleTruncate = function(){
  truncateText = !truncateText;
};

查看:

<p class="forum-content" id="{{post.id}}" ng-bind-html="renderHtml(post.content)"></p>

<button class="button button-block" ng-click="toggleTruncate()">Toggle Truncate</button> 

【讨论】:

    猜你喜欢
    • 2015-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-23
    相关资源
    最近更新 更多