2013-05-16 129 views
0

我有一个这样的控制器:如何从控制器的外部调用一个函数在控制器

function MyCtrl($scope) { 

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

} 

而且我有依赖此多个视图(即下面的倍数):

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

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

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

现在,我想基本上调用DoSomething的()函数,这是内部MyCtrl,从dataIsReady()函数。我怎样才能做到这一点?

+0

我不知道angularJS,但其他语言的答案是将函数移到外部作用域,然后从两个地方调用它。 –

回答

4

我想你需要的是一个数据服务,然后你就可以注入到控制器。你可以调用你的数据服务的一个函数来处理数据的检索,并返回一个“承诺”,这个承诺可以用来在数据加载时触发你的回调函数。 看一看下面的代码是从egghead.io略加修改:

Plunker演示(W /本地存储):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; 
     });    

}); 

希望有所帮助。

+0

感谢您的回复!有没有更简单的方法可以做到这一点?我的应用程序是一个非常简单的CRUD应用程序,我不希望Angular JS的东西使它复杂化得超过必要的程度......我也不介意如果简短的代码明智的快速入侵(也就是说,该div并运行该功能)。我试图在保持某种一致性标准的同时快速创建应用程序原型。虽然我理解了上面所有的代码,但我只是有一堆控制器正在等待一些数据在后台加载。 – oxuser

+0

@oxuser:对不起,我不确定你说的“范围到div”是什么意思。如果你设置了一个jsfiddle或plunker,我很乐意为你寻找。另一种可能的方法是将数据服务添加到'$ rootScope'并使用'$ broadcast'来通知所有监听控制器何时使用'$ scope。$ on'检索数据。看到这里的例子:[http://jsfiddle.net/gavinfoley/XCeK3/](http://jsfiddle.net/gavinfoley/XCeK3/) – GFoley83

2

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

既然你已经在MyCtrl定义$scope.doSomething

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

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

相关问题