Question

I have experience using the Knockout framework.

What is the cleanest way one would write the code below in Angular ?

The code below is Knockout code which describes a car inventory object that contains an array of car objects.

There are probably multiple ways of doing this in Angular. If you know of a way and it's not listed here, please present it.

The genesis of this question came from a debate my colleague and I had at work about whether Angular is more elegant than Knockout. I asked him the same question I state here and he couldn't answer me ,after a few days, which implies that it's really hard or not possible (which I doubt).


<script type='text/javascript' src='knockout-3.1.0.js'></script>

<script>
function tire() {

    var self = this;
    //write properties and methods about tire here
}

function door() {

    var self = this;
    //write properties and methods about door here
}


function engine( car_parent ) {

    var self = this;
    //write properties and methods about engine here
}


function car() {

    var self = this;

    self.tires = [new tire(), new tire(), new tire(), new tire() ];
    self.doors = [new door(), new door(), new door(), new door() ];

    //below gives the engine child access to its car parent
    self.engine = new engine(self);

    //write other properties and methods about a car here

}


function carInventory() {
    var self = this;
    self.cars = [new car(),  new car(), new car()];

    //write properties and methods about the car inventory here
}

var vm = new carInventory();
ko.applyBindings(vm);

</script>   
Was it helpful?

Solution

I don't see much in your sample that would be different in Angular. Instead of the ko.applyBindings(vm) in Knockout, you would wire up your view model inside a controller in Angular:

var app = angular.module('App',[])
.controller('Controller1', function($scope){
    $scope.inventory = new carInventory();
}); 

One primary difference with Angular is that you don't have to make the properties on your objects into observables and computeds.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top