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:



The Subscribe:

First challenge was to find the Angular equivalent of a knockout observable subscribe:

this was get from the Knockoutjs documentation:

http://knockoutjs.com/documentation/observables.html

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 https://docs.angularjs.org/guide/scope

$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); });

Computed:

The second challenge I faced was to convert the KnockoutJs computed to AngularJs equivalent: http://knockoutjs.com/documentation/computedObservables.html

//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; $scope.$watch( 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; }); }, true );

Update:

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 😉