2015-04-19 51 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

相关问题