我有一个简单的 Angular 应用程序,我正在尝试对其进行设置,以便当人们单击图像时,会显示一条加载消息,然后当图像加载时,它会隐藏。
当我删除 scope.loading = false;
时,会显示该消息(显然),但是当我有该行时,该消息永远不会显示,即使图像需要 5 秒以上的时间才能显示加载。
谁能看出问题所在吗?
app.controller('ProductsCtrl', function($scope, $interval) {
$scope.images = LayerData['images'];
$scope.mainImage = '/open/img/'+$scope.images[0].section+'/'+$scope.images[0].file;
$scope.loading = true;
$scope.main = function(img) {
$scope.mainImage = '/open/img/'+img.section+'/'+img.file;
}
});
app.directive('imageonload', function($timeout) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('load', function() {
scope.$apply(function() {
scope.loading = false;
});
});
scope.$watch(function () { return scope.mainImage; }, function (newValue) {
if (newValue) {
scope.loading = true;
element.attr('src', scope.mainImage);
}
});
element.attr('src', scope.mainImage);
}
};
});
相关的 HTML 就是这样,但如果您需要/想查看其余部分,请告诉我
<div class="row wrapper" ng-controller="ProductsCtrl">
<div col>
<div row>
<div col>
<h1>{$section.title}</h1>
</div>
</div>
</div>
{literal}
<div col>
<div row>
<div col lg="7" md="7">
<p ng-show="loading">Loading image...</p>
<div id="mainImage">
<img ng-src="{{mainImage}}" imageonload style="max-width:100%;" />
</div>
</div>
<div col lg="5" md="5">
{/literal}
{$sidebar}
{literal}
</div>
</div>
</div>
<div col class="imgList">
<div class="scrolls">
<div class="imageDiv">
<img src="/assets/media/img/{{img.section}}/thumb-100-{{img.file}}" ng-click="main(img)" ng-repeat="img in images" />
</div>
</div>
</div>
{/literal}
</div>
这是使用 Smarty 和 Angular 的混合,因此这就是 {literals} 和 {$...} 的用途。
最佳答案
您正在绑定(bind)到 link
中 Angular 框架之外的浏览器 DOM 事件。您的功能imageonload
指令。
您需要通过发出$apply来通知Angular变量更新。 .
link: function(scope, element, attrs) {
element.bind('load', function() {
scope.$apply(function() {
scope.loading = false;
});
});
}
编辑
您正在绑定(bind) src
<img>
的属性之前imageonload
指令绑定(bind)到加载事件。
<img ng-src="{{mainImage}}" imageonload style="max-width:100%;" />
相反,去掉 ng-src
在 HTML 中声明并将其设置在 imageonload
中指令,您可以在其中确保首先绑定(bind)加载事件。
像这样:
<img imageonload style="max-width:100%;" />
然后设置src
绑定(bind)调用后应该有望解决您的问题:
link: function(scope, element, attrs) {
// Bind to load event (Same code as as above)
// Set src attribute here *after* binding to the load event
element.attr('src', scope.mainImage);
}
关于javascript - 变量似乎没有更新其值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24317051/