Bryan Fritchie Bryan Fritchie - 4 months ago 9
AngularJS Question

angular and binding to a key

My data looks something like this:

$scope.Statuses = [
{"status_id":1, "status":"A"},
{"status_id":2, "status":"B"},
{"status_id":3, "status":"C"},
];

$scope.Items= [
{"item_id":1, "item":"X", "status_id":3},
{"item_id":2, "item":"Y", "status_id":2},
{"item_id":3, "item":"Z", "status_id":1},
];


In my HTML, I am looping through the Items and displaying them in a grid. So at one point I am trying to accomplish something like this:

<div>{{Statuses[Item.status_id]}}</div>


For Item "X" I'd expect to see a status of "C", etc. It seems like it should be more like, "Statuses[status_id = Item.status_id]}}", but for the life of me I can't find anything like this. Is this even possible? I can return the "status" with the Item if I have too, but that seems to defeat the purpose in this case, plus it potentially messes up other things later on.

In fact, as I write this I can already see that even if I get the key matching (status_id = Item.status_id), I'm not telling it which field it would need to display to get the correct results.

Answer

Something like this:

var app = angular.module('MyApp', []);

app.controller('AppCtrl', function($scope) {
    $scope.Statuses = [
      {"status_id":1, "status":"A"},
      {"status_id":2, "status":"B"},
      {"status_id":3, "status":"C"},
    ];

    $scope.Items = [
       {"item_id":1, "item":"X", "status_id":3},
       {"item_id":2, "item":"Y", "status_id":2},
       {"item_id":3, "item":"Z", "status_id":1},
    ];

    $scope.getStatus = function (val) {
        var foundStatus = $scope.Statuses.filter(x => x.status_id === val)[0];
        return foundStatus.status;
    };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>

<div ng-controller="AppCtrl" ng-cloak="" ng-app="MyApp">
    <div ng-repeat="item in Items">
        <div ng-bind="item.status_id"></div>
        <div ng-bind="getStatus(item.status_id)"></div>
    </div>
</div>

Note: you can of course use {{getStatus(item.status_id)}}, but I do not like such approach, because in this case your end-user might see {{}} if you client scripts takes some time to perform some actions, like AJAX calls, for instance. Yes, there is ng-cloak directive which assists to solve the issue, but I personally do not like it and it is off-topic in this question.