I know we can achieve conditional binding with ng-repeat
through the following:
<tr ng-repeat="viewer in allViewers track by viewer.Id">
<td>
<img width="18" ng-src="{{!viewer.StatusByUser || viewer.StatusByUser != 1 ?
'/images/icons/hide.svg' : '/images/icons/show-18x11.png'}}"
onerror="this.src='/images/icons/hide.svg'" alt="Viewer Status"
title="Click to {{!viewer.StatusByUser || viewer.StatusByUser != 1 ?
'publish' : 'unpublish'}}" ng-click="manageViewerStatus(viewer.StatusByUser)">
</td>
</tr>
But as you can see, this is messy and in reality, I have at least 5 to 6 status to keep track of and change the display image icon accordingly.
In JavaScript, we know that there is a way to pass the current element to a function:
<img src="/images/icon.jpg" onclick="changeAttr(this)" />
But in Angular, I tried the following but not working:
In HTML:
<img data-bind="{{renderStatusImg(this, viewer)}}" width="18" alt="Viewer Status"
title="Click to publish" ng-click="manageViewerStatus(viewer.StatusByUser)">
In controller:
$scope.renderStatusImg = function (img, viewer) {
$(img).attr("src", !viewer.StatusByUser || viewer.StatusByUser != 1 ? '/images/icons/hide.svg' : '/images/icons/show-18x11.png');
// More complex logic can be written here in future to cater for more status.
return viewer.Id;
};
As a result, viewer.Id
can be returned and rendered in data-bind
attribute, but the src
attribute isn't rendered. I have heard of the directive approach but seems like it can only deal with the indexes of the underlying data and not the element itself. Any help will be appreciated, thank you.