我试图实现数据绑定到指令内服务返回的值.
我有它工作,但我跳过篮球,我怀疑有更好的方法.
例如:
<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; } }; });
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。