Not everything in AngularJS has a KnockoutJS equivalent (for example ngCloack
, or ngSrc
). There are two main solutions typically available:
attr
or event
binding instead.If you prefer the AngularJS binding syntax you can consider using Knockout.Punches which enables handlebar-style binding.
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>
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>
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" />
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.
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>