My current implementation is shown below which is working but as the getImage method is inside expressions its being called repeatedly when any text change or data is entered on the page
HTML
<div ng-repeat="product in pageData.products">
<div>
<img style="width:60px;" ng-src={{getImage(product)}} />
</div>
</div>
JS:
$scope.getImage = function(product)
{
var image = Utils.getLocalStorageEntityByIdFromList(product.ID,"ProductID", "images");
if(image) return image.Data;
else return "";
};
I am trying put getImage method inside a .directive as most posts are suggesting and pass product as parameter inside the directive. Post link How to call a function in "ng-src"
I am new to AngularJS, any help in putting the getImage method in a directive where the product parameter can be passed I will be really thankful.
Something along these lines shown below..
JS:
angular.module('MyApp', [])
.controller('Ctrl2', function($scope) {
})
.directive('mySrc', function() {
return {
restrict: 'A',
link: function ( scope, elem, attrs ) {
var image = Utils.getLocalStorageEntityByIdFromList(product.ID,"ProductID", "images");
elem.attr('src', image.Data);
}
};
});
HTML:
<div ng-app="MyApp">
<div ng-controller="Ctrl2">
<div ng-repeat="product in pageData.products">
<div><img my-src="product" /><div>
</div>
</div>
Many thanks for your time.
To avoid multiple calls to a function in an AngularJS Expression, use one-time binding:
<div ng-repeat="product in pageData.products">
<div>
<!-- REPLACE This
<img style="width:60px;" ng-src={{getImage(product)}} />
-->
<!-- WITH One time binding -->
<img style="width:60px;" ng-src={{::getImage(product)}} />
</div>
</div>
One-time bindings are especially useful in ng-repeat
contents because they significantly reduce the number of active watchers.
From the Docs:
One-time binding
An expression that starts with
::
is considered a one-time expression. One-time expressions will stop recalculating once they are stable, which happens after the first digest if the expression result is a non-undefined value (see value stabilization algorithm below).
-- AngularJS Developer Guide -- Expressions -- One-time Binding