knockout.js

Equivalents of AngularJS bindings

Remarks#

Not everything in AngularJS has a KnockoutJS equivalent (for example ngCloack, or ngSrc). There are two main solutions typically available:

  1. Use the generic attr or event binding instead.
  2. Similar to custom directives in AngularJS, you can write your own custom binding handler if you need something that isn’t included in the base library.

If you prefer the AngularJS binding syntax you can consider using Knockout.Punches which enables handlebar-style binding.

ngShow

AngularJS code for dynamically showing/hiding an element:

<p ng-show="SomeScopeProperty">This is conditionally shown.</p>

KnockoutJS equivalent:

<p data-bind="visible: SomeScopeObservable">This is conditionally shown.</p>

ngBind (curly markup)

AngularJS code for rendering plain text:

<p>{{ ScopePropertyX }} and {{ ScopePropertyY }}</p>

KnockoutJS equivalent:

<p>
  <!-- ko text: ScopeObservableX --><!-- /ko --> 
  and 
  <!-- ko text: ScopeObservableY --><!-- /ko --> 
</p>

or:

<p>
  <span data-bind="text: ScopeObservableX"></span> 
  and 
  <span data-bind="text: ScopeObservableY"></span>
</p>

ngModel on input[type=text]

AngularJS code for two-way binding on a text input:

<input ng-model="ScopePropertyX" type="text" />

KnockoutJS equivalent:

<input data-bind="textInput: ScopeObservableX" type="text" />

ngHide

There is no direct equivalent binding in KnockoutJS. However, since hiding is just the opposite of showing, we can just invert the example for Knockout’s ngShow equivalent.

<p ng-hide="SomeScopeProperty">This is conditionally shown.</p>

KnockoutJS equivalent:

<p data-bind="visible: !SomeScopeObservable()">This is conditionally hidden.</p>

The above KnockoutJS example assumes SomeScopeObservable is an observable, and because we use it in an expression (because of the ! operator in front of it) we cannot omit the () at the end.

ngClass

AngularJS code for dynamic classes:

<p ng-class="{ highlighted: scopeVariableX, 'has-error': scopeVariableY }">Text.</p>

KnockoutJS equivalent:

<p data-bind="css: { highlighted: scopeObservableX, 'has-error': scopeObservableY }">Text.</p>

This modified text is an extract of the original Stack Overflow Documentation created by the contributors and released under CC BY-SA 3.0 This website is not affiliated with Stack Overflow