gpt4 book ai didi

javascript - 调用 $scope 函数的自定义指令导致 $rootScope :infdig

转载 作者:搜寻专家 更新时间:2023-11-01 04:35:52 25 4
gpt4 key购买 nike

我曾尝试在这里查看其他 $rootScope:infdig 问题,但找不到真正向我解释清楚或我理解的问题。与 AngularJs 文档相同。我希望有人能提供帮助。

我在 $scope 上创建了一个函数,它接受一个参数并调用一个 api GET 请求并返回一个只有“id”和“name”的 json 对象。然后,此函数将对象的名称返回给调用它的指令。

该函数从指令中调用,但一旦执行,它就会陷入每秒一百个这样的“rootScope:infdig”错误中。该指令也从不呈现返回的“名称”的文本。我知道 http 调用有效,因为之后我在控制台中记录了“名称”。

Error Screen

这是我的 Controller :

owlyfm.controller('landingPageController', [ "$scope", "$log", "$http", "$location", "apiUrlsService", function ($scope, $log, $http, $location, apiUrlsService) {

$http.get("https://api.backand.com:443/1/objects/Albums?pageSize=3&pageNumber=1&deep=true&relatedObjects=true")
.success( function(result){
$scope.featuredAlbums = result.data;
//$log.info($scope.featuredAlbums);
})
.error( function(data, status){
$log.error(data);
});

$scope.getAlbumArtist = function(artistId){

$http.get("https://api.backand.com:443/1/objects/Artists/" + artistId)
.success(function(result){
var artistsName = result.name;
$log.info(artistsName);
return artistsName;
});
}
}]);

这是我创建指令的地方:

owlyfm.directive("featuredAlbum", function(){

return{
restrict: 'E',
templateUrl: 'directives/featuredAlbum.html',
scope: {
albumObject: "=",
getAlbumArtistFunction: "&"
}
}
});

这里是我在 View 中调用指令的地方

<div class="row fluid-container" >
<featured-album ng-repeat="featuredAlbum in featuredAlbums" album-object="featuredAlbum" get-album-artist-function="getAlbumArtist(album)" class="col-md-4" ></featured-album>
</div>

这是指令本身:

    <div class="featuedAlbum">

<div>
<img class="img-responsive" ng-src=" {{albumObject.albumArtUrl}} "/>
</div>

<h4>{{ albumObject.name }}</h4>
<h5>{{ getAlbumArtistFunction( { album: albumObject.Artists } ) }}</h5>
<h6>{{ albumObject.releaseDate }}</h6>

</div>

我在做什么

总而言之,我正在做的是调用 api 来获取专辑对象,(顺便说一句,我正在使用“Backand”)一旦我得到这个专辑对象,我就会渲染 <img><h>带有我收到的数据的标签。一切正常。

专辑对象具有 ID、名称、日期、imgUrl 和“艺术家”(这只是艺术家的 ID)。然后我使用这个“艺术家”ID 进行另一个调用以获取与其关联的实际艺术家对象。这就是问题所在。

问题

导致错误循环的是对艺术家对象的 http 调用。尽管我可以在日志中看到它正在获取艺术家的 json 对象,但它不会将其发送到指令。

我研究了什么

我读到过将 ng-repeat 与指令中的函数一起使用时会出现问题。但是,我不太完全理解为什么以及如何将它应用在这里,也不知道我将如何更改它来实现我想要实现的目标。这里的所有其他问题都超出了我的理解范围。

如果有人能帮助我,我将不胜感激。

最佳答案

正如评论中所说,调用一个将从服务器内部 View 中获取数据的函数不是一个好主意,因为它会调用多次,而您只需要调用一次。

您可以添加将在“featuredAlbum”构造函数中设置的“artistName”属性。


owlyfm.controller('featuredAlbumController', [ "$scope","$http",function ($scope, $http) {
$http.get("<a href="https://api.backand.com:443/1/objects/Artists/" rel="noreferrer noopener nofollow">https://api.backand.com:443/1/objects/Artists/</a>" + $scope.artistId)
.success(function(result){
$scope.artistName = result.name;
});
}]);

因此,$http 只会在 Controller 第一次运行时被调用一次。

关于javascript - 调用 $scope 函数的自定义指令导致 $rootScope :infdig,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34714129/

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