2013-05-16 46 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方法。

相關問題