【问题标题】:Component isn't refreshing scope on $emit组件没有在 $emit 上刷新范围
【发布时间】:2020-02-21 22:00:53
【问题描述】:

我在 AngularJS 中有一个组件,其值保存到范围内,该范围为视图中的 <img> 提供 URL。当用户更改图片时,控制器会通过$rootScope.$emit 发出更改,并且 URL 值会更新,显示新上传图片的视图也应该更新:

angular.module('ppApp').component('mainnav', {
    templateUrl: 'app/templates/nav/nav.main-nav.tpl.htm',
    controller: ['$scope', function($scope){

        vm.avatarimage = '../p3sweb/avatarImage';

        $rootScope.$on('refreshAvatar', function(){
           console.log('change avatar')
           vm.avatarimage = '../p3sweb/avatarImage';
        })

    }]
})

//Controller
$rootScope.$emit('refreshAvatar',function(){ //value refreshAvatar emitted when they have loaded new image

})

//view
<img data-ng-src="{{$ctrl.avatarimage}}" alt="users profile pic" class="profile-pic-radius">

发射被拾取并记录了“更改头像”,但图像在我刷新页面后不会更新。

问题

如何仅刷新组件,以便它更新范围并显示刚刚上传的新图像?

【问题讨论】:

    标签: angularjs components


    【解决方案1】:

    这不是 Angular.js 的问题,但您需要一个技巧来更新您的图像,因为 img 标记在其源更改之前不会更新。

    您可以在图像源 URI 的末尾添加时间戳。

    ...
        $rootScope.$on('refreshAvatar', function(){
            console.log('change avatar')
            // SEE HERE!!!
            var timestamp = new Date().getTime();
            vm.avatarimage = '../p3sweb/avatarImage' + '?' + timestamp;
        })
    ...
    

    【讨论】:

    • 很高兴。很高兴对您有所帮助。
    • 也享受你的周末:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-01
    • 2018-01-05
    • 1970-01-01
    • 2020-03-18
    • 2020-09-16
    • 1970-01-01
    • 2016-07-10
    相关资源
    最近更新 更多