AngularJS Images multiple Requests

I am currently developing an AngularJS application.

Everything is working fine except loading an image.

I have used the following call in my view:

<img ng-src="img/views/portrait/{{employee.lastName|lowercase}}.jpg" title="{{employee.lastName}}"/>

Now the strange thing is, that there are 2 requests fired:

http://localhost:8080/MyContext/content/img/views/portrait/.jpg

and

http://localhost:8080/MyContext/content/img/views/portrait/example.jpg

The first one has empty values for employee.lastName. I can't explain myself why this is happening, although I am using the ng-src directive.

Any ideas?

Thanks in advance for your support.

My Resource Code

var employeeService = $resource('/MyContext/rest/employees/:employeeId', {}, {});
employeeService.findById = function(id) {
    return employeeService.get({employeeId:id});
};

in the controller I call:

$scope.employees = EmployeeService.findAll();

Are you loading the employee data using the $resource service? If so, the $resource service will first return an empty object which would explain the first request. As soon as the data from the server is received, that data will be copied into the previously empty object and trigger an update of the bound values. In your case that would be the ng-src of the img and that would trigger the second request.

If you don't want to use success callback of the $http you can ad a watcher on employee.lastName :

First choose a default picture in your controller :

$scope.defaultPicture = '/MyContext/content/img/views/portrait/default.jpg'

Use it in your view :

<img ng-src="{{ defaultPicture }}" title="{{ employee.lastName }}"/>

Then ad a watcher on employee.lastName :

$scope.$watch('employee.lastName', function(lastName) {
        if (lastName) {
            $scope.defaultPicture = '/MyContext/content/img/views/portrait/'+lastName+'.jpg;
        }
    });

Done, there is a call made to get the default picture which will be cached by the browser, and when the resource employeeService is ready the image will automatically change.

I just did it in my project.