2015-04-19 49 views
0

我對angular很陌生,我仍然遵循教程和內容來解決問題。我需要一些幫助以下。 我有一個看起來像這樣的控制器。如何從另一個控制器調用控制器的服務在Angular JS中成功回調

app.controller('ScheduleBooking', ['$http', function($http){ 
    var schedule = this; 
    schedule.databooking = []; 

    $http.post('../getbookings.json'). 
     success(function(data, status, headers, config) { 
      schedule.databooking = data; 
     }). 
     error(function(data, status, headers, config) { 
      console.log('failed'); 
     }); 

}]); 

調用$ http服務獲取預訂列表和HTML中的控制器我用ng-repeat填充響應。

我有另一個這樣的控制器。

app.controller('MakeBooking', ['$http', function($http){ 
    var makeBooking = this; 
//somecode here 

    $http.post('../MakeBooking.json?name=burhan'). 
     success(function(data, status, headers, config) { 
      // I WANT TO REFRESH THE LIST OF BOOKINGS. 
//I am looking a way to call scheduleBooking controller so that 
//it can make http call and refresh the list of booking in html. 
     }). 
     error(function(data, status, headers, config) { 
      console.log('failed'); 
     }); 

}]); 

因此情景是:當頁面加載客戶應該看到他已經完成的所有預訂。當他進行預訂時,會呼叫http服務進行預訂,並且在此服務成功回叫時,我想要執行某些操作,以便通過調用計劃預定控制器中定義的http服務來刷新預訂列表。 也許我可以用BROADCAST和ON方法做到這一點。但我不確定。在我已有的JQuery書面應用程序中發生了很多類似的事情。 這樣做的最佳方式是什麼?也許我正在採取這種完全錯誤的做法,還有其他更好的辦法。 你們建議什麼?

回答

0

由於ScheduleBooking似乎沒有做多的呼叫端點最好的辦法就是把它變成服務,(從中或獲取數據)注入在每次需要調用特定的方法控制這個服務要多得多,這樣的事情:

app.factory('ScheduleBookingSerice', ['$http', function($http){ 

    var schedule = this; 

    schedule.getBookings = function(callback){$http.post('../getbookings.json'). 
     success(function(data, status, headers, config) { 
      callback(data); 
     }). 
     error(function(data, status, headers, config) { 
      console.log('failed'); 
     }); 
    } 
    return schedule; 
}]); 


app.controller('MakeBooking', ['$http', 'ScheduleBookingSerice', function($http, ScheduleBookingSerice){ 
    var makeBooking = this; 
//somecode here 

    $http.post('../MakeBooking.json?name=burhan'). 
     success(function(data, status, headers, config) { 
      ScheduleBookingSerice.getBookings(function success(data){ 
      //operate on your data here 
      }); 
     }). 
     error(function(data, status, headers, config) { 
      console.log('failed'); 
     }); 

}]); 
+0

謝謝你回答問題。 問題是MakeBooking控制器不依賴於預定日程的數據。我不想在製作控制器中操作日程預約控制器的數據。我只是想提醒從makebooking控制器的計劃預訂控制器運行一次(以便它可以更新** schedule.databooking **數組和DOM更新。) 獲得我的觀點? –

+0

那麼在這種情況下,一切都取決於您如何在頁面上構建控制器。如果他們在父 - 子關係,那麼你可以嘗試用$ scope調用它。$ parent如果不是,那麼廣播似乎是最好的方式,但我仍然相信你可以避免這種情況,最好是注入服務(或者如果它必須是控制器,你可以注入$控制器回答我們它描述http://stackoverflow.com/questions/25417162/how-do-i-inject-a-controller-into-another-controller-in-angularjs – maque

相關問題