4

I'm trying to acheive databinding to a value returned from a service inside a directive.

I have it working, but I'm jumping through hoops, and I suspect there's a better way.

For example:

<img my-avatar>

Which is a directive synonymous to:

<img src="{{user.avatarUrl}}" class="avatar">

Where user is:

$scope.user = CurrentUserService.getCurrentUser();

Here's the directive I'm using to get this to work:

.directive('myAvatar', function(CurrentUser) {
    return {
        link: function(scope, elm, attrs) {
            scope.user = CurrentUser.getCurrentUser();
// Use a function to watch if the username changes,
// since it appears that $scope.$watch('user.username') isn't working
            var watchUserName = function(scope) {
                return scope.user.username;
            };
            scope.$watch(watchUserName, function (newUserName,oldUserName, scope) {
                elm.attr('src',CurrentUser.getCurrentUser().avatarUrl); 
            }, true);
            elm.attr('class','avatar');

        }
    };

Is there a more succinct, 'angular' way to achieve the same outcome?

2
  • As silly as this might be.... could it be that $scope.$watch('user.username') should be scope.$watch('user.username')? Commented Dec 24, 2012 at 13:21
  • @MathewBerg thanks for catching that - unfortunately it's just a typo in the post. Commented Dec 25, 2012 at 5:31

1 Answer 1

4

How about this ? plunker

The main idea of your directive is like

.directive('myAvatar', function (CurrentUserService) {
        "use strict";
        return {
            restrict: 'A',
            replace: true,
            template: '<img class="avatar" ng-src="{{url}}" alt="{{url}}" title="{{url}}"> ',
            controller: function ($scope, CurrentUserService) {
                $scope.url = CurrentUserService.getCurrentUser().avatarUrl;
            }
        };
    });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.