AngularJS Single Value Mapping With Directives and Filter

In some scenarios, the JSON models that we have available on the client browser may not provide all necessary information for our view templates. A record may just have a numeric value which makes reference to another model in the system, and we need to be able to map or look up for that information. To illustrate this, let’s look at a dealership inventory vehicle list:


$scope.cars = [{ model: 'Altima', year: 2015, make: '1' },
            { model: 'XTerra', year: 2015, make: '2' },
            { model: 'Focus', year: 2015, make: '3' }];

$scope.makes = [{ id: 1, name: 'Toyota' },
                { id: 2, name: 'Nissan' },
                { id: 3, name: 'Ford' }];

The models show a list of makes and vehicles that any dealership may have an inventory. We want to build a view that shows the vehicle list. When using the cars list and the help of the ng-repeat directive as show below, we get this result.

As we can see, there is no Make 1,2,3. That is the MakeId. We would like to display the name instead. The problem with this is that the cars list only has the id, so we need to implement a look up with the makes list. A way to do this is to use another ng-repeat directive with the help of a filter. This way we can tell the filter to only get the make that has the corresponding id. We can make the following changes and see the results:

We can see on the results that we are now showing the make name not the id. 

We should note that this approach was done on the HTML mark-up using directives. A second approach can be done using JavaScript and the ng-init directive to add a dynamic property to our collection. Read about it here.

Thanks for reading.


Post a Comment

What do you think?