A
A
Alexey Aristov2016-08-22 18:24:09
Angular
Alexey Aristov, 2016-08-22 18:24:09

AngularJS: Is it possible to create an objectById reference to use in templates?

There are resources:

app.service('rest', function($resource) {
    return {
      account: $resource('/rest/account', {}, {
        get: {method: 'GET', isArray: true}
      }),
      product: $resource('/rest/product', {}, {
        get: {method: 'GET', isArray: true}
      }),
    };
  });
After the products have loaded, they are displayed in the interface:
<li ng-repeat="product in vendorProductList">
  {{product.acc_id}} {{product.descr}}
</li>

But I need to display not acc_id, but acc_name from the account reference.
How to create an accountById reference and refer to it from a template?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Aristov, 2016-08-26
@aristov

It turned out that I was trying to invent a bicycle and everything worked without unnecessary manipulations.
Add a directory to $rootScope:

app.service('rest', function($resource, $rootScope) {
    $rootScope.refBook = {
      account: {}
    };
    return {
      account: $resource('/rest/account', {}, {
        get: {
          method: 'GET', isArray: true,
          interceptor: {
            response: function(resp) {
              var data;
              for (var i=0; i<resp.data.length; i++) {
                data = resp.data[i];
                $rootScope.refBook.account[data.id] = data;
              }
            }
          }
        }
      }),

and this reference is available in templates:
<li ng-repeat="product in vendorProductList">
{{refBook.account[product.acc_id].name}} - {{product.descr}}
</li>

D
Daniil Sorokin, 2016-08-22
@DanSorokin

Personally, I created another method in the service, which added a new field (in your case, product.acc_name) where the necessary information is written. Then this method in the controller pulled up the data. I don't know how right it is

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question