AngularJS:绑定内部指令

时间:2012-12-24 05:32:25

标签: angularjs

我正在尝试将数据绑定转换为指令内服务返回的值。

我有它的工作,但我正在跳过篮球,我怀疑还有更好的方法。

例如:

<img my-avatar>

这是指令的同义词:

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

user的位置:

$scope.user = CurrentUserService.getCurrentUser();

这是我用来实现这个目的的指令:

.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');

        }
    };

是否有更简洁,更有棱角的方式来达到同样的结果?

1 个答案:

答案 0 :(得分:4)

这个怎么样? plunker

你的指令的主要思想是

.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;
            }
        };
    });