0

I have an animation directive that uses scope.$watch to listen for a change on it's attribute, in this case the directive itself. The problem is I need to manipulate parent scope variables from inside of the $watch or the animation function. Inside my directive, but outside of the watch, the scope, element, and attrs parameters are defined. Inside of the $watch only the element is defined and the scope and attrs are not.

app.directive('animateGif', function ($animate) {
  return {
    restrict: 'A',
    link: function (scope, element, attrs) {
      // scope, element, and attrs are defined here
      scope.$watch(attrs.animateGif, function(runAnim) {
        // only element is defined here
        if (runAnim) {
          $animate.addClass(element, 'animLargenerGif', function() {
            // a child scope is defined here
            console.log("add class callback in directive");
          });
        } else {
          $animate.removeClass(element, 'animLargenerGif', function() {
            console.log("remove class callback in directive");
          });
        }
      });
    }
  };
});

Alternatively, I would like to manipulate the parent scope from within the animation function. I found some advice on year of moo http://www.yearofmoo.com/2013/05/enhanced-animations-in-angularjs.html#using-scope-in-your-js-animations, which has worked for me in the past in the "enter" animation function, but for some reason the scope that I'm able to access does not hold scope functions from the controller on which the parent scope is defined. Any advice on this would be greatly appreciated.

app.animation('.animLargenerGif', function() {
  var elm, $scope, parent;
  var getScope = function(e) {
    return angular.element(e).scope();
  };
  return {
     addClass : function(element, className, done) {
      $scope = getScope(elm).$parent;
      elm = element[0];
      setTimeout(function() {
        $(elm).transition({ y: '-440px' }, 800, 'linear', function() {
          setTimeout(function() {
            $scope.animationSetter($scope.largenerObj.animElm);  // this function is unavailable but the $scope.largenerObj is defined -- only if I call get scope inside of the timeout
            $scope.$apply();
            done();
          }, 1000);
        });
      }, 0);
    },
    removeClass : function(element, className, done) {
      console.log("class removed", className);
      done();
    }
  }
});

1 Answer 1

0

You can use the $timeout service and $scope.$apply to edit the parent scope on callback

$timeout(function() {
    scope.$apply(function() {
        scope.foo = "bar";
    });
});
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.