小编典典

呈现值,无需数据绑定

angularjs

在AngularJS中,如何在不进行2向数据绑定的情况下呈现值?出于性能方面的考虑,甚至可能在给定的时间点呈现值,可能要这样做。

以下示例均使用数据绑定:

<div>{{value}}</div>

<div data-ng-bind="value"></div>

我如何在value 没有任何 数据绑定的 情况下 进行渲染?


阅读 298

收藏
2020-07-04

共1个答案

小编典典

角度1.3+

在1.3中,Angular使用以下语法支持此功能。

<div>{{::message}}</div>

正如在这个答案中提到的。


Angular 1.2以下

这很简单,不需要插件。看一下这个。

这个小指令可以轻松完成您要实现的目标

app.directive('bindOnce', function() {
    return {
        scope: true,
        link: function( $scope ) {
            setTimeout(function() {
                $scope.$destroy();
            }, 0);
        }
    }
});

你可以这样绑定一次

<div bind-once>I bind once - {{message}}</div>

你可以像平常一样绑定

<div ng-bind="message" bind-once></div>

演示:http//jsfiddle.net/fffnb/

你们中的某些人可能正在使用有角batarang,并且如注释中所述,如果使用此指令,则该元素在未使用时仍显示为绑定,我很确定这与附加到该元素的类有关。试试这个,它应该可以工作
(未经测试) 。请在评论中让我知道它是否对您有用。

app.directive('bindOnce', function() {
    return {
        scope: true,
        link: function( $scope, $element ) {
            setTimeout(function() {
                $scope.$destroy();
                $element.removeClass('ng-binding ng-scope');
            }, 0);
        }
    }
});

@ x0b:如果您具有OCD,并且要删除空class属性,请执行此操作

!$element.attr('class') && $element.removeAttr('class')
2020-07-04