AngularJS:绑定内部指令

前端之家收集整理的这篇文章主要介绍了AngularJS:绑定内部指令前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图实现数据绑定到指令内服务返回的值.

我有它工作,但我跳过篮球,我怀疑有更好的方法.

例如:

<img my-avatar>

这是一个指令的同义词:

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

用户在哪里:

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

        }
    };

是否有更简洁,“棱角分明”的方式来实现相同的结果?

解决方法

这个怎么样 ? 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;
            }
        };
    });

猜你在找的Angularjs相关文章