如何使用Angular动态更新img src

时间:2015-07-30 20:37:33

标签: angularjs

我有一个图片库,我想让他们打开一个" zoomable"点击/点击时的版本。

除了让zoom-image src更新外,我已经完成了所有工作。

这是我在控制器中的代码。

// setup array of images and preset the zoom-image
$scope.zoomPictureSrc = '';
angular.forEach($scope.trayDetails.tray_images, function(trayImage) {
    var myBase64 = "data:image/png;base64,"+trayImage.data;
    var img = new Image();
    img.src = myBase64;
    $scope.savedPictures.push(img);
    if ($scope.zoomPictureSrc === '') {
        $scope.zoomPictureSrc = img.src;
    }
});

// set the new zoom-image src & open the divs
$scope.zoomDisplay = false;
$scope.zoomOpen = function (source) {
    $scope.zoomPictureSrc = source;
    $scope.zoomDisplay = true;
    $scope.$evalAsync();
};
// close the zoom image divs
$scope.zoomClose = function () {
    $scope.zoomDisplay = false;
};

这是我认为的

<ul class="tray-photos clearfix">
    <li ng-repeat="savedPicture in savedPictures" class="photo">
        <span class="photo-container" ng-click="zoomOpen(savedPicture.src)"><img ng-controller="TrayDetailsCtrl" ng-src="{{savedPicture.src}}" /></span>
    </li>
</ul>
<div class="zoom-background" ng-show="zoomDisplay"></div>
<div class="zoom-wrap" ng-show="zoomDisplay">
    <div class="zoom-container">
        <span class="zoom-content photo-container" ng-click="zoomClose()"><img ng-controller="TrayDetailsCtrl" hm-pinchin="pinchIn" hm-pinchout="pinchOut" ng-src="{{zoomPictureSrc}}" /></span>
    </div>
</div>

zoom-xxx div显示和隐藏,但img本身没有改变。我已尝试使用和不调用$ scope的代码。$ evalAsync();

1 个答案:

答案 0 :(得分:1)

您正在调用同一个控制器两次,这将创建具有两个不同范围的控制器。尝试这样的事情:

<div ng-controller="TrayDetailsCtrl">
    <ul class="tray-photos clearfix">
        <li ng-repeat="savedPicture in savedPictures" class="photo">
            <span class="photo-container" ng-click="zoomOpen(savedPicture.src)"><img ng-src="{{savedPicture.src}}" /></span>
        </li>
    </ul>
    <div class="zoom-background" ng-show="zoomDisplay"></div>
    <div class="zoom-wrap" ng-show="zoomDisplay">
        <div class="zoom-container">
            <span class="zoom-content photo-container" ng-click="zoomClose()"><img hm-pinchin="pinchIn" hm-pinchout="pinchOut" ng-src="{{zoomPictureSrc}}" /></span>
        </div>
    </div>
</div>

我将它包装在一个控制器中。如果由于某种原因需要维护单独的控制器,则需要找到一种在它们之间共享数据的方法。与服务或工厂一样。