gpt4 book ai didi

javascript - div 中的图像动态填充

转载 作者:行者123 更新时间:2023-12-03 05:29:46 25 4
gpt4 key购买 nike

我需要通过迭代对象(ng-repeat)动态填充图像

请找到下面的代码

<div class="row graph-img">
<div class="col-sm-6" ng-repeat="option in subserviceObject.serviceRequest">
<img ng-init="retreiveGraph(service,subservice,$index)" id="imgframe{{$index}}" src="">
</div>
</div>

我的 Controller 代码在这里

$scope.retreiveGraph = function(serviceName,subservice,index) {
$scope.service=serviceName;
$scope.resetGrapghParam(serviceName,subservice,num);
$scope.displayServiceDetails(serviceName);
imgsrc='./service/getServiceDetails/'+$scope.service+'/'+$scope.initGrapghServiceName;
document.getElementById("imgframe"+index).setAttribute("src", imgsrc);
};

我在控制台中收到错误,例如“无法读取 null 的属性‘setAttribute’”。

如果这是解决此解决方案的错误方法,请建议我解决此问题。

请在渲染后找到我的最终 HTML 元素

<div class="row graph-img">
<!-- ngRepeat: option in subserviceObject.serviceRequest --><div class="col-sm-6 ng-scope" ng-repeat="option in subserviceObject.serviceRequest">
<img ng-init="retreiveGraph(service,subservice,$index)" id="imgframe0" src="">
</div><!-- end ngRepeat: option in subserviceObject.serviceRequest -->
<div class="col-sm-6 ng-scope" ng-repeat="option in subserviceObject.serviceRequest">
<img ng-init="retreiveGraph(service,subservice,$index)" id="imgframe1" src="">
</div><!-- end ngRepeat: option in subserviceObject.serviceRequest --><div class="col-sm-6 ng-scope" ng-repeat="option in subserviceObject.serviceRequest">
<img ng-init="retreiveGraph(service,subservice,$index)" id="imgframe2" src="">
</div><!-- end ngRepeat: option in subserviceObject.serviceRequest -->
</div>

id 填充正确,但当我尝试 setAttribute 时,它​​返回 null

提前致谢

最佳答案

Angular 有一个指令来构造 img 标签的 src,使用它:

<div class="row graph-img">
<div class="col-sm-6" ng-repeat="option in subserviceObject.serviceRequest">
<img ng-src="retreiveGraph(service,subservice,$index)">
</div>
</div>

然后在你的 Controller 中:

$scope.retreiveGraph = function(serviceName, subservice, index) {
$scope.service=serviceName;
$scope.resetGrapghParam(serviceName,subservice,num);
$scope.displayServiceDetails(serviceName);
return './service/getServiceDetails/' + $scope.service + '/' + $scope.initGrapghServiceName;
};

虽然我认为你误解了 Angular 的一些概念,比如 $scope 等。我建议您在继续之前阅读一些文档...

您不需要在每次迭代时将参数传递到函数中,如果您将它们放在 $scope 对象上,您可以直接从那里获取它们。

关于javascript - div 中的图像动态填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40995343/

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