Search code examples
javascriptangularjsng-animate

AngularJS : Call controller function from outside with vm


Here I have :

var app = angular.module('app');
app.controller("myController", function () {
        var vm = this;
        vm.myFunction = function() { alert('foo'); };
});

app.animation('.animate', ["$timeout", function($timeout) {
      var vm = this;
      return {
        addClass: function(element, className, doneFn) {
            $timeout(function() {
                console.log('this is displayed');
                vm.myFunction(); // Doesn't work !
            });
        }
      }
}]);

When I add a class in the template, addClass gets fired. However, vm.myFunction() doesn't, because it does not exist.

How do we do this in angular ?


Solution

  • Some different from yours but I thought this can help you...

    in HTML
    
    <div id="outer" ng-controller="myController"></div>
    
    in JS
    
    var app = angular.module('app');
    app.controller('myController', function ($scope) {
    
     $scope.myFunction = function() { alert('foo'); };
    
    });
    
    var scope = angular.element($("#outer")).scope();
    scope.myFunction();