【问题标题】:AngularJS : How to do ng-bind logic check?AngularJS:如何进行 ng-bind 逻辑检查?
【发布时间】:2015-04-27 19:47:00
【问题描述】:

我收到了一些推文数据,有时数据库会根据服务器(本地、生产等)返回不同的 JSON 对象。

有时推文内容在tweets[i].text,有时在tweets[i].highlights.text

我当前的标记:

<section ng-repeat="t in tweets">
    <div ng-bind-html="t.text">{{t.text}}</div>

    <!-- <div ng-bind-html="t.highlights.text">{{t.highlights.text}}</div> -->

如果t.text 存在,有没有办法签入ng-bind?如果没有,则将模型设置为t.highlights.text?

ng-if:


在 div 上使用 ng-if 来呈现列表中的实际推文:

<section ng-repeat="t in tweets" class="social-content">
    <a href="http://twitter.com/{{t.fields.user_name}}/status/{{t.id}}" target="_blank">
        <header>
            <em>+</em>
            <span>@{{t.fields.user_name}}</span>
        </header>
        <div class="body" ng-if="t.text != undefined" ng-bind-html="t.text">{{t.text}}</div>
        <div class="body" ng-if="t.highlights.text != undefined" ng-bind-html="t.highlights.text">{{t.highlights.text}}</div>
    </a>
    <time>{{t.fields.formatted_date_difference}} ago</time>
</section>

【问题讨论】:

  • 可以使用ng-ifng-switch或者一个简单的指令设置html而不是使用ng-bind-html
  • 您可以使用 ngIf 进行检查,但可能需要修改一些标记。 docs.angularjs.org/api/ng/directive/ngIf
  • 推文总是一种形式还是另一种形式,或者它们可以混合出现吗?
  • 如果它们混合在一起,我建议在将它们放入控制器数组之前将它们标准化为一个结构,这样你就不必使用 switch/if 逻辑来丑化视图。
  • @LeonGaban 如果要使用ng-if 属性,并且它们都是相同的结构,我不会将ng-if 放入重复的div,而是有两个重复列表,并在控制器isHighlights 中设置一个布尔值来检查第一条推文。 ng-if=isHighlighted 到第一个列表,!isHighlighted 到第二个列表。更少的绑定,更容易记忆。

标签: javascript angularjs angularjs-ng-repeat angularjs-ng-model


【解决方案1】:

根据 Ben 的建议,这根本不应该在视图中,它应该在负责呈现数据模型以供视图呈现的控制器中。

$scope.tweets.forEach(function(t) {
    t._content = t.text || t.highlights.text || '';
});

然后在您的视图中渲染 t._content 而不是 t.text 等。

【讨论】:

  • 哦,嗯...是的,我认为这更好
  • 嗯遇到了问题,我想我可以让这个工作,如果我这样做我会检查这个..会 bbl
  • 我必须检查以确保 t.highlights.text 不是 undefined 但这是一种更简洁的方法,在模型数据到达标记之前:)
【解决方案2】:

控制器:

$scope.isHighlights = false;

$scope.tweets = [];

$scope.getTweets = $http.get('url').then(function(data){
   //Get first tweet and set isHighlighted bool based on the property being defined
    $scope.isHighlighted = angular.isDefined(data[0].highlights);
    $scope.tweets = data;
});

查看:

<div data-ng-if="isHighlights">
    <section data-ng-repeat="t in tweets">{{t.highlights.text}}</section>
</div>

<div data-ng-if="!isHighlights">
    <section data-ng-repeat="t in tweets">{{t.text}}</section>
</div>

这在内存上更轻,绑定更少,并且对于其他检查代码的人来说更容易阅读。有一百万种方法可以剥这只猫的皮。这种方式假设它们都是一种格式或另一种格式,并且一个屏幕上可能有很多推文。

【讨论】:

  • 维护噩梦!
  • @randomsock 如果section 中的 html 变得更复杂,那么是的,我同意。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-12
  • 2015-11-30
相关资源
最近更新 更多