LoginSignup
48
51

More than 5 years have passed since last update.

AngularJSのOne Time Binding使用例

Posted at

digestループ内の処理を軽くして高速化を実現出来るone-time-bindingが1.3から導入されました。しかし、簡単なサンプルしかネットでは拾えない気がしたのでよく使う使用例をまとめてみます。

基本

<p ng-bind="::message"></p>
<p>{{ ::message }}</p>

一番シンプルなパターン

filter

<p ng-bind="::website_url | linky"></p>

filterをかませるときも同様

ng-repeat

<div ng-repeat="list in ::lists">
  <p ng-bind="::list"></p> <!-- ここにも -->
</div>

配列名の前に::を付ける。加えて、ループ内の要素にも::を付けるとその要素分bindingを減らせる

ng-class

<span ng-class="::{'selected': is_seleted}">hoge</span>

::is_selectedと書きたくなるが、curlyの前に::を置くのが正解

ng-if, ng-show, ng-switch

<div ng-if="::user.is_sageman"></div>
<div ng-if="::!user.is_sageman"></div> <!-- 否定 -->
<div ng-show="::user.is_ageman"></div>

<div ng-switch="::tribe_type">
  <p ng-switch-when="exile">EXILE</p>
  <p ng-switch-when="jsoulbro">J Soul Brothers</p>
  <p ng-switch-when="egirls">E Girls</p>
</div>

ng-if,ng-switchの論理評価も対象にできる。ng-switch-whenは元々bindingに含まれていない

<div ng-if="::(is_ageman && is_ikemen)"></div>

::is_ageman && ::is_ikemenではなく、全体を括弧で括ってその前に::を付ける
is_ageman && ::is_ikemenにように片方だけ::を付けることは出来ない

不等式

<div ng-if="::(count > 0)"></div>

上と同様に括弧で括ります

directive

<div tag-cloud tags="::tags"></div>
.directive('tagCloud', function() {
  return {
    template:"<div ng-repeat=\"tag in ::tags\"><p>{{ ::tag }}</p></div>",
    scope: { tags: "=" }
  };
})

directive内のtemplateでone time bindingが使えるのはもちろんだが、
directiveに渡すscopeにも::を付けてtags=::tagsとするとひとつbindingを減らせる

まとめ

これくらいを抑えておけば、だいたいのケースには対応出来るはずです

48
51
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
48
51