我正在使用Codrops的GridLoadingEffects库和Angular JS为它提供来自wordpress的数据列表项目。一切都是通过$http请求从角度检索数据,并异步存储变量。数据被处理并通过ng-bind-html绑定到HTML。
<body ng-app="myApp">
<div class="container" ng-controller="myController">
<ul class="grid effect-6" id="grid" ng-bind-html="bindHTML(html_code)"></ul>
</div>
</body>在检索数据导致的轻微延迟之后,我可以看到HTML实际上被加载到检查器中的DOM中。然而,问题是GridLoadingEffects效果立即发现DOM中没有列表项,因此抛出一个未定义的错误。
我不是一个有经验的web开发人员,所以我不能准确地确定在哪里进行调用来检查DOM的li元素并应用效果,而且这个库有许多依赖项,包括modernizr.js、masonry.js、imagesloaded.js、AnimOnScroll.js等等。更让我困惑的是,这些文件加载在HTML中的不同位置,一些在头部,另一些在主体的末尾。所以就执行流程而言,我真的不知道如何解决这个问题。我不确定,但我认为这个函数是实例化效果的。
<script>
window.onload = function() {
new AnimOnScroll( document.getElementById( 'grid' ), {
minDuration : 0.4,
maxDuration : 0.7,
viewportFactor : 0.2
} );
}
</script>根据Codrops提供的示例html文件,它将被放在正文的末尾。我认为为了纠正这个问题,一旦Angular将数据提供给ul标签,就必须运行上面的函数。即使有一个window.onload附加到它上面,它可能也不会考虑使用angular加载更多内容。
我的假设正确吗?我相信有一个简单的解决方法。有人能帮上忙吗?
更新:以下是$http请求的发起方式:
(function() {
'use strict'
angular.module('myApp', [])
.controller('myController', myController);
myController.$inject = ['$scope', '$sce','$http']
function myController ($scope, $sce, $http) {
$http({
method : "GET",
url : myURL
})
.then(function(response) {
$scope.myData = response.data;
var list = new Array
for (var i = 0; i < $scope.myData.length; i++) {
var string = '<li><figure class="blurfilter semitransparent"><img src=myURL><figcaption><h3>' + $scope.myData[i]['title']['rendered'] + '</h3></figcaption></figure></li>';
list.push(string)
}
$scope.html_code = list.join("")
$scope.bindHTML = function(html_code) {
return $sce.trustAsHtml(html_code)
};
});
};
})();更新2:
我的HTML现在使用ng-repeat来分离模型和视图:
<li ng-repeat="(key, val) in myData">
<h3>{{val.title.rendered}}</h3>
</li>和我的angular代码(省略了http请求):
(function() {
'use strict'
angular.module('myApp', [])
.controller('myController', myController);
myController.$inject = ['$scope', '$sce','$http']
function myController ($scope, $sce, $http) {
$scope.$watch('myData', function() {
// if the myData is loaded
if ($scope.myData.length > 0) {
new AnimOnScroll( document.getElementById( 'grid' ), {
minDuration : 0.4,
maxDuration : 0.7,
viewportFactor : 0.2
});
}
});现在我知道$scope.myData是未定义的。$scope.myData是在我的http请求的.then中定义的。提到这个错误指向angular.min.js文件中的一行,而不是我的app.js,可能会有所帮助。
发布于 2018-08-29 23:07:57
在使用$http服务获取数据后,您可以尝试在角度控制器中对数据变量使用$scope.$watch函数。
$scope.$watch('myData', function() {
// if the myData is loaded
if ($scope.myData && $scope.myData.length > 0) {
// your code
}
});发布于 2018-08-30 18:59:09
我知道我的问题有点偏离了在检索数据之后运行函数,而是在检索的数据填充了DOM之后运行函数。对于遇到同样问题的任何人(不是在检索数据时,而是在检索并填充DOM之后),您需要使用指令。查看这篇文章:ng-repeat finish event。你的解决方案就在这里。
https://stackoverflow.com/questions/52080483
复制相似问题