2
votes

I think that I'm having scope problems that I'm not able to fix, here is an explanation of my problem.

I want to create my own directive "my-create-content" to insert an "img" HTML template in the element where the directive had been defined. Then, I've defined ng-show in "img" and a timeout that evaluates ng-show to false, but after timeout "img" element is no hidden. I'm not sur if it's a scope problem because ng-src="{{imageUrl}}" it's evaluated correctly.

Here's my code:

.directive('myCreateContent', [function() {

function link(scope, element, attrs) {

  scope.showImg = false;

  function updateImg(url){
    scope.imageUrl = url;
    scope.showImg = true;
  }

  if (scope.grid[0].image){
    updateImg(scope.grid[0].imageUrl);
    setTimeout(function(){
      scope.showImg = false;
    }, scope.grid[0].duration);
  }

}

return {
  scope: {
    grid: '='
  },
  template: '<img ng-show="showImg" ng-src="{{imageUrl}}" class="grid">',
  link: link
};
}]);

And the HTML:

<div my-create-content grid="grid" class="container">
2
did you loaded the javascript in the html? - anish
Inject and use $timeout in place of setTimeout. - AlwaysALearner

2 Answers

1
votes

You need to call $apply for AngularJS to understand scope variables have changed.

In this case, instead of using setTimeout, you should use $timeout which will take care of everything for you.

Read more here: $timeout service

1
votes

You have to use $timeout, because it's ensure that it's gonna be digested and thus rendered.

You could also use $apply inside the setTimeout, but it's not the best option because you could trigger some javascript error if AngularJS is already digesting

I put your code on jsfiddle:

http://jsfiddle.net/g07stzdk/3/

Reading your code, I think you are working on a carousel. If this is correct, the right function ub your code would be: $interval which is the equivalent of setInterval in plain javascript