简体   繁体   English

Angular JS监视服务方法中的数据

[英]Angular JS watch data from a service method

So I have a service that gets a json object which is working fine. 所以我有一个服务,它可以正常工作的json对象。 In my controller, I want to watch that object for any changes. 在我的控制器中,我想监视该对象的任何更改。 When there is a change in the object, i want that to update on the fly in the UI. 当对象发生变化时,我希望在用户界面中进行动态更新。 Here is my service: 这是我的服务:

angular.module('vertopsappApp.services', [])
.factory('vertopsappAppAPIservice', function($http) {

var vertopsappAppAPI = {};

vertopsappAppAPI.getDrivers = function() {
  return $http({
    method: 'JSONP',
    url: 'http://faboolis.com/example.json?callback=JSON_CALLBACK'
  });
}

return vertopsappAppAPI;
 });

My controller looks like this but I'm pretty sure its not the way to do this. 我的控制器看起来像这样,但是我很确定它不是这样做的方法。

 .controller("LineCtrl", function ($scope, vertopsappAppAPIservice) {
   $scope.$watch('vertopsappAppAPIservice.getDrivers()', function (newVal) {
    console.log('data changes into: ', newVal)
   }, true);
 });

any help would be much appreciated. 任何帮助将非常感激。 Thanks in advance. 提前致谢。

You could try emitting an event from the service when your data changes, and listening to the same in your controller and hence update your model so that the UI changes. 您可以尝试在数据更改时从服务中发出事件,并在控制器中侦听事件,从而更新模型以使UI更改。

Edit with example : 用示例编辑

Inside Service when your data changes: 数据更改时的内部服务:

$rootScope.$emit("value_changed", newValue); //trigger this when you know there is a change in value

Inside controller: 内部控制器:

$rootScope.$on("value_changed", function(e,newValue) { $scope.urUIVariable = newValue; });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM