简体   繁体   English

如何在AngularJS中使用Service获得双向数据绑定?

[英]How to get two-way data binding with a Service in AngularJS?

I do a query to a JSON file and with the result I make a table, but as this file is updated very frequently, I need to see constantly if this file has suffered changes to show them in a real time application. 我对JSON文件进行查询,并生成一个表,但由于该文件更新非常频繁,因此我需要不断查看此文件是否发生了更改,以便在实时应用程序中显示它们。

I have tried many things with AngularJS but every time has result in fails. 我已经用AngularJS尝试了很多东西,但是每次都导致失败。

This is my code: 这是我的代码:

app.js app.js

(function(){
   var myapp = angular.module("appMonitor",[]);


   myapp.factory('myService', function($http,$timeout) {
      var promise;
      var myService = {
         get: function() {
             if ( !promise ) {
                 // $http returns a promise,
                 // which has a then function, which also returns a promise
                 promise = $http.get('./json/verifyEmpty.json').then(function (response) {
                 // The then function here is an opportunity to modify the response
                 console.log(response.data);
                 // The return value gets picked up by the then in the controller.
                 return response.data;
                 });
              }
              // Return the promise to the controller
              return promise;
           }
        };
      return myService;
    });


    myapp.controller('monitorCtrl', function(myService,$scope) {
    // Call the async method and then do stuff with what is returned inside our own then function
        myService.get().then(function(d) {
            $scope.response = d;
        });
    });

})();

verifyEmpty.json verifyEmpty.json

[
  { "name":"luis", "lastname":"perez", "age":27, "gender":"m", "haircolor":"yellow", "eyecolor":"brown", "student":false },
  { "name":"monse", "lastname":"chuang", "age":28, "gender":"f", "haircolor":"black", "eyecolor":"black", "student":true },
  { "name":"sarah", "lastname":"lee", "age":29, "gender":"f", "haircolor":"yellow", "eyecolor":"green", "student":true },
  { "name":"luisa", "lastname":"ortega", "age":28, "gender":"f", "haircolor":"black", "eyecolor":"blue", "student":false },
  { "name":"lorenza", "lastname":"garcia", "age":27, "gender":"f", "haircolor":"brown", "eyecolor":"brown", "student":true }
]

monitor.php monitor.php

 <body ng-app="appMonitor">
    <div class="" ng-controller="monitorCtrl">
    <table>
       <tr>
          <th><strong>name</strong></th>
          <th><strong>lastname</strong></th>
          <th><strong>age</strong></th>
          <th><strong>gender</strong></th>
          <th><strong>haircolor</strong></th>
          <th><strong>eyecolor</strong></th>
          <th><strong>student?</strong></th>
       </tr>

       <tr ng-repeat="r in response" ng-cloak>
          <td>{{r.name}}</td>
          <td>{{r.lastname}}</td>
          <td>{{r.age}}</td>
          <td>{{r.gender}}</td>
          <td>{{r.haircolor}}</td>
          <td>{{r.eyecolor}}</td>
          <td ng-show="r.student">Yes</td>
        </tr>


    </table>
       <!-- {{response}} -->
    </div>
    <script type="text/javascript" src="./js/148libraries/angular.min.js"></script>
    <script type="text/javascript" src="./js/app.js"></script>
 </body>

You can't do exactly what you want, but you can achieve something similar. 不能完全按照自己的意愿去做,但是可以实现类似的目的。

With the code that you have posted, you are retrieving the JSON contents just one time. 使用已发布的代码,您只需一次即可检索JSON内容。 So, I imagine that in your complete code, that you are constantly executing the $http.get() and pooling the JSON files after X seconds using setTimeout() or something similar. 因此,我想像一下,在您完整的代码中,您会不断执行$http.get()并在X秒后使用setTimeout()或类似方法来合并JSON文件。 This is the easiest way, but not the most efficient. 这是最简单的方法,但不是最有效的。

Since your JSON file is hosted in another machine, your Angular code, that runs in the client's browser can't know when the file has changed. 由于您的JSON文件托管在另一台计算机上,因此在客户端浏览器中运行的Angular代码无法知道文件何时更改。 It must be warned by someone else. 必须由其他人警告。

In this case, the first thing you need to implement at the server-side is a routine that is triggered when the JSON file changes. 在这种情况下,您需要在服务器端实现的第一件事是在JSON文件更改时触发的例程。 For this task, as it seems that you are using PHP, you can take a look at inotify and this answer . 对于此任务,似乎您正在使用PHP,可以看一下inotify和这个答案

The second part is to implement a Streaming approach in Angular instead of a Pooling mechanism. 第二部分是在Angular中实现Streaming方法,而不是Pooling机制。 Since I don't know the PHP tools very well, I can't find one right now to suggest to you. 由于我不太了解PHP工具,因此我现在找不到适合您的建议。 If you could use Node, I would suggest you to take a look at Pusher and in this tutorial . 如果可以使用Node,建议您看一下Pusher和本教程

With this approach, you would set a Node server to be listening to changes in your JSON file and your Angular service to be listening to Node. 使用这种方法,您可以将Node服务器设置为侦听JSON文件中的更改,并将Angular服务设置为侦听Node。 Whenever the file is changed, it will trigger the Node and Angular to update your table view. 每当文件更改时,它将触发节点和角度更新表视图。

Note : its a one-way data bind. 注意 :它是单向数据绑定。 A two-way data bind would be to $watch for variable changes made by your users at the browser and when $watch receives an event, you would make a $http call to update the JSON file. 双向数据绑定将是$ watch来查找用户在浏览器上所做的变量更改,并且$ watch收到事件时,您将进行$ http调用以更新JSON文件。

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

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