KnockoutJs computed equivalent AngularJs

Table of Content

Recently, I had to work in a project, where I had the opportunity of convert a DurandalJS (KnockoutJs) application into AngularJs, and I faced a couple of challenges that I would like to share with you:
KnockoutJs computed equivalent AngularJs

The Subscribe:

First challenge was to find the Angular equivalent of a knockout observable subscribe:
this was get from the Knockoutjs documentation:

var myViewModel = {
    personName: ko.observable('Bob')

myViewModel.personName.subscribe(function(oldValue) {
    alert("The person's previous name is " + oldValue);
}, null, "beforeChange");

KnockoutJs computed equivalent AngularJs

This is what I found as result of my research (this is the AngularJs equivalent) Using the $scope.$watch method see the AngularJs life cycle

$scope.myViewModel = {
personName: 'Bob'

$scope.$watch(‘myViewModel.personName’, function(newValue, oldValue){
//we are able to have both the old and the new value
alert("The person's previous name is " + oldValue);



The second challenge I faced was to convert the KnockoutJs computed to AngularJs equivalent:

//knockout computed
var isVendorLoading = ko.observable(),
isCustomerLoading = ko.observable(),
isProgramLoading = ko.observable(),
isWaiting = ko.observable();

var isDataLoading = ko.computed(function () {
return isVendorLoading() || isCustomerLoading() || isProgramLoading() || isPositionLoading() || isWaiting();


This is the AngularJs Equivalent for KnockoutJs computed:

$scope.isDataLoading = false;
function (scope) {
//those are the variables to watch
return { isVendorLoading: scope.isVendorLoading, isCustomerLoading: scope.isCustomerLoading, isProgramLoading: scope.isProgramLoading, isWaiting: scope.isWaiting };
function (obj, oldObj) {
$timeout(function () {
//$timeout used to safely include the asignation inside the angular digest processs
$scope.isDataLoading = obj.isVendorLoading || obj.isCustomerLoading || obj.isProgramLoading || obj.isPositionLoading || obj.isWaiting;


Based on the comment David Gee below I decide to write an article about using Object.defineProperty with custom getter and setters to achieve the same result in a more optimal way, you can read it here:
Optimizing code using Object.defineProperty instead of $scope for $watch in AngularJs

Hope this was helpful 😉