加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

AngularJS:绑定内部指令

发布时间:2020-12-17 17:17:40 所属栏目:安全 来源:网络整理
导读:我试图实现数据绑定到指令内服务返回的值. 我有它工作,但我跳过篮球,我怀疑有更好的方法. 例如: img my-avatar 这是一个指令的同义词: img src="{{user.avatarUrl}}" class="avatar" 用户在哪里: $scope.user = CurrentUserService.getCurrentUser(); 这
我试图实现数据绑定到指令内服务返回的值.

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

例如:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读