【问题标题】:How to update angular data without refreshing the page?如何在不刷新页面的情况下更新角度数据?
【发布时间】:2018-03-24 19:55:58
【问题描述】:

我在数据库表中有一些数据,我使用 Angular 来显示它。我使用以下脚本在页脚中来做到这一点:

 <script !src="">
var app = angular.module('enterprise', []);

app.controller('entercontroller', function($scope, $http){

    $scope.loadData= function(){

        $http.post('<?php echo base_url(); ?>Groups_/load_data')
            .then(function(mydata){
                console.log(mydata);

                $scope.datas = mydata.data;

            });
    };
    $scope.loadData();
});
</script>  

我的控制器中的 load_data() 函数如下:

 public function load_data(){
    $data["groups"] = $this->Groups->fetch_groups();
    return $this->output
    ->set_status_header(200)
    ->set_content_type('application/json', 'utf-8')
    ->set_output(json_encode($data["groups"], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
}

我的观点是一些带有提交按钮的输入。我需要的是当我单击按钮添加新记录时,表格会自动更新,而无需每次刷新页面。所以我制作了另一个脚本来这样做

 <script>
$(document).ready(function() {
$('#add').on('submit', function() {
    var that = $(this);
    $dataString = that.serialize();             
    $.ajax({
        url: '<?php echo base_url(); ?>'+ $("#uri").val() ,
        type: 'POST',
        dataType: 'json',
        cache:false,
        data : $dataString,
        success: function (data) {
            console.log(data);
            $('#message').html(data['message']);
            $(':input','#add')
              .removeAttr('checked')
              .removeAttr('selected')
              .not(':button, :submit, :reset, :hidden, :radio, :checkbox')
              .val('');
        },
        error: function (data) {
            console.log('error');
            console.log(data);
        }
    });
    return false;            
});
});
</script>

HTML 代码如:

<div class="page-wrapper" ng-app="enterprise" ng-controller="entercontroller">
<div class="container-fluid">
<div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-block">
                    <form class="floating-labels m-t-40" method="post" id="add" action="addgroup">
                        <div class="form-group m-b-40">
                            <input type="text" name="group_title" class="form-control input-lg" id="input8" required><span class="bar"></span>
                            <label for="input8">Group Name</label><br />
                        </div>

                        <div class="form-group m-b-40">
                            <input type="text" name="group_link" class="form-control input-lg" id="input7" required><span class="bar"></span>
                            <label for="input7">Link</label>
                        </div>

                        <div class="form-group m-b-40">
                            <select name="group_icon_code" class="custom-select form-control" id="location1" required >
                                <option value="">Icon</option>
                                <?php
                                if(isset($icons))
                                    foreach($icons as $icon)
                                        echo '<option value="'.$icon->icon_value.'">'.$icon->icon_name.'</option>';
                                ?>
                            </select>
                        </div>

                        <div class="text-xs-right">
                            <input type="hidden" id="uri" name="uri" value="Groups_/addgroup" />
                            <button type="submit" ng-click="loadData()" name="add" value="1" class="btn btn-success"> <i class="fa fa-check"></i> save</button>
                            <button type="reset" class="btn btn-inverse"> <i class="fa fa-times"></i> cancel</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
<div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-block">
                    <div class="table-responsive">
                        <table class="table color-bordered-table inverse-bordered-table">
                            <thead>
                                <tr>
                                    <th>title</th>
                                    <th>link</th>
                                    <th>order</th>
                                    <th>icon</th>
                                    <th class="text-nowrap">control</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr ng-repeat="d in datas">
                                    <td>{{ d.group_title }}</td>
                                    <td>{{ d.group_link }}</td>
                                    <td>{{ d.group_order }}</td>
                                    <td><i class="mdi {{ d.group_icon_code }}"></i></td>
                                    <td class="text-nowrap">
                                        <a href="#" data-toggle="tooltip" data-original-title="Edit"> <i class="fa fa-pencil text-inverse m-r-10"></i> </a>
                                        <a href="#" data-toggle="tooltip" data-original-title="Delete"> <i class="fa fa-close text-danger"></i> </a>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
  </div>
</div>

我曾尝试将 Angular 脚本放在点击功能中,但它不起作用。 我需要的是在添加后再次重新加载相同的位置。 任何想法。

【问题讨论】:

  • 首先准备api,然后准备view,在那里进行ng-repeat,然后,发出api请求放东西,api请求获取数据并放回模型。不需要 jQuery。看看任何一个待办事项应用程序,它是如何制作的。

标签: javascript jquery angularjs codeigniter


【解决方案1】:

AngularJS 主要用于双向数据绑定,这似乎是您正在寻找的。如果您使用 Angular,则不需要使用 JQuery 来更新数据。 $scope 中声明的所有变量在更改时会自动刷新


因此,您在加载角度控制器时已经在发布数据。 我会将它包含在附加到范围的函数中,因此在单击按钮时,您可以发布您的对象,然后将其插入表格中。

var app = angular.module('enterprise', []);

app.controller('entercontroller', function($scope, $http){
  $scope.tableData = [{ text: "First row" }, { text: "second row" }];

  $scope.loadData = function () {
    // here you do your http post
    var newRow = { text: "New Row" };
    $scope.tableData.push(newRow); // do this inside your http callback function
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js">
</script>
<body ng-app="enterprise" ng-controller="entercontroller">
  <table>
    <tr ng-repeat="row in tableData">
      <td>
        {{row.text}}
      </td>
     </tr>
  </table>
  <button ng-click="loadData()">
    Load data
  </button>
</body>

【讨论】:

  • 我只是编辑我的问题,只有角脚本部分与您告诉我的方式相同,但它会创建新的 &lt;tr&gt;&lt;/tr&gt; 和空的 &lt;td&gt;&lt;/td&gt;。我不知道你是否正确地回答了我的问题。我需要在我的数据库中添加的新记录显示在浏览器的表格中。我想当我调用获取我的数据的控制器函数时,它就是它。无论如何谢谢。
  • 如果你想在表格中显示你发布的对象,这是要走的路。 {{row}} 引用了一个字符串。如果您有一个对象,则必须为要显示的每个属性编写&lt;td&gt; {{row.attribute}} &lt;/td&gt;。此外,您不应该将您的帖子放在函数之外,因为这将在您的脚本加载时执行帖子。
  • ng-repeat 属性会自动将您发布的对象添加到表格中。
  • 我已经按照你说的做了。问题是当我添加新记录时。只有新记录根本不出现,只有在我刷新页面时才会出现。好像它跳过 $http.post('http://localhost/clinic/Groups_/load_data') 再次加载。
  • 您是否将 ng-click 标签添加到您的按钮?如果您需要更多帮助,查看您的 html 代码会很有帮助
【解决方案2】:

如果您只想在事务后刷新表中的数据列表,可以使用此脚本。您不需要在添加按钮上添加刷新功能。在您的负载数据上使用它。

angular.module('app', [])
.controller('ctrl', function($scope, $timeout) {

  $scope.IntervalTime = 2000;
  $scope.updatedData = 0;

  timeoutFn();

  function timeoutFn() {
    $timeout(function() {

      //Add your select data query here

      $scope.updatedData++; 

      timeoutFn();

    }, $scope.IntervalTime);
  }
})
<script src="//unpkg.com/angular/angular.js"></script>
<div ng-app='app' ng-controller='ctrl'>
    <table style="width:50%; height: 50%;">
       <tr>
          <th>Data</th>
       </tr>

       <tr>
          <td>{{updatedData}}</td>
       </tr>
    </table>
</div>
<style>
    table, th, td {
         border: 1px solid black;
         text-align: center;
    }
</style>

注意:您的表格将每 2 秒刷新一次并加载更新的选择数据,因为我将其设置为 $scope。您可以根据需要更改间隔。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-15
    • 2014-08-18
    • 1970-01-01
    • 1970-01-01
    • 2017-06-13
    • 2017-03-24
    • 1970-01-01
    相关资源
    最近更新 更多