gpt4 book ai didi

AngularJS:绑定(bind)内部指令

转载 作者:行者123 更新时间:2023-12-02 11:28:07 25 4
gpt4 key购买 nike

我正在尝试将数据绑定(bind)到从指令内的服务返回的值。

我已经可以使用它了,但我正在经历困难,我怀疑有更好的方法。

例如:

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

}
};

是否有更简洁、“有 Angular ”的方式来实现相同的结果?

最佳答案

这个怎么样? 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:绑定(bind)内部指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14017448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com