如何从控制器外部调用控制器中的功能

时间:2013-05-16 00:18:13

标签: angularjs

我有一个像这样的控制器:

function MyCtrl($scope) {

  $scope.doSomething = function(){
    alert("Do something!");
  }

}

我有多个视图依赖于此(即下面的多个):

  <div ng-controller="MyCtrl">
    ...
  </div>

问题是,控制器所依赖的数据需要在后台加载(控制器不加载该数据),并在数据准备好后调用回调(dataIsReady())。

function dataIsReady(){
  // TODO: call the doSomething() function
}

现在,我想从dataIsReady()函数中调用doSomething()函数,该函数位于MyCtrl中。我怎么能这样做?

2 个答案:

答案 0 :(得分:4)

我认为您需要的是数据服务,然后您可以将其注入控制器。您可以在数据服务上调用一个函数来处理数据检索并返回一个“promise”,然后可以在加载数据时触发回调函数。 看看下面的代码,它是egghead.io的一个稍微修改过的版本:

Plunker Demo(带本地存储空间): http://plnkr.co/edit/9w2jTg?p=preview

var myApp = angular.module('myApp', []);

myApp.factory('AvengersService', function ($http) {

    var AvengersService = {
        getAsyncCast: function () {           
            // $http returns a promise, which has a then function, which also returns a promise
            var promise = $http.get("avengers.json") // or some JSON service
                .then(function (response) {
                   // The 'then' function here is an opportunity to modify the response
                   // The return value gets picked up by the 'then' in the controller.
                   return response.data;
            });
            // Return the promise to the controller
            return promise;
        }
    };

    return AvengersService;
});

myApp.controller('AvengersCtrl', function($scope, AvengersService) {
    // Call the async method and then do something when the data is retrieved
    AvengersService.getAsyncCast()
        .then(function (asyncData) {
            // Callback logic that depends on the data goes in here
            console.info("Cast pulled async.");
            $scope.avengers.cast = asyncData;
        });              

});

希望有所帮助。

答案 1 :(得分:2)

注意:此答案中的这种方法非常错误,不应该在角度之外或控制器之外访问控制器的范围。如果您尝试多次调用它,这也会非常慢。除此之外,没关系。我给出了这个答案,因为它也是最简单的方法。但是我永远不会在生产中使用那种代码。适当的方法是编写服务以与控制器通信。

鉴于您已在$scope.doSomething中定义MyCtrl

var scp = angular.element('[ng-controller="MyCtrl"]').scope();
scp.doSomething();

将调用控制器中定义的doSomething方法。

相关问题