简体   繁体   中英

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 ?

Modify your code as the following:

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

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

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM