javascript - Variable not seeming to update its value -
i have simple angular app, i'm trying set when person clicks on image, loading message shown, when image loads, hides.
when remove scope.loading = false;, message shown (obviously), when have line, message never shown, if image takes 5+ seconds load.
can see what's wrong?
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) { homecoming { restrict: 'a', link: function(scope, element, attrs) { element.bind('load', function() { scope.$apply(function() { scope.loading = false; }); }); scope.$watch(function () { homecoming scope.mainimage; }, function (newvalue) { if (newvalue) { scope.loading = true; element.attr('src', scope.mainimage); } }); element.attr('src', scope.mainimage); } }; }); the relevant html this, if need/want see rest allow me know
<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> this using mixture of smarty , angular that's {literals} , {$...} for.
you're binding browser dom event outside of angular framework in link function of imageonload directive.
you need notify angular of variable update issuing $apply.
link: function(scope, element, attrs) { element.bind('load', function() { scope.$apply(function() { scope.loading = false; }); }); } edit
you're binding src attribute of <img> before imageonload directive binds load event.
<img ng-src="{{mainimage}}" imageonload style="max-width:100%;" /> instead, rid of ng-src declaration in html , set within imageonload directive, can ensure load event gets bound first.
like so:
<img imageonload style="max-width:100%;" /> and setting src after bind phone call should solve problem:
link: function(scope, element, attrs) { // bind load event (same code as above) // set src attribute here *after* binding load event element.attr('src', scope.mainimage); } javascript angularjs
No comments:
Post a Comment