AngularJS : 使用 vm 从外部调用控制器函数

AngularJS : Call controller function from outside with vm

我这里有:

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 !
            });
        }
      }
}]);

当我在模板中添加 class 时,addClass 被触发。但是,vm.myFunction() 没有,因为它不存在。

我们如何在 angular 中做到这一点?

修改您的代码如下:

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 !
            });
        }
      }
}]);

有些与您不同,但我认为这可以帮助您...

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