繁体   English   中英

将条目插入数据库后如何更新模型? 并刷新视图

[英]How update model after inserting entry to database? And refresh a view

我害羞地试图使Angular和后端数据库成为朋友。

操作简单。 获取数据库到角度模型。 将条目保存在数据库中,然后删除条目。

我堆积在DELETE动作上。 当我删除从数据库加载的条目时就可以了。 但是当我通过push方法删除新创建的行时,出现错误。

发生这种情况是因为模型中没有ID。 将条目插入数据库后,我尝试反复从数据库刷新Angular模型。($ http.get)但是在这种情况下,视图没有刷新(仅闪烁)。 我看到新条目仅刷新页面F5。

救命!

图书

   <div ng-app="App" ng-controller="MyCtrl">


    <table class="">
        <th>
            <tr style="font-size: 20px">
                <td>ID</td>
                <td>Name</td>
                <td>Price</td>
                <td>Action</td>
            </tr>
        </th>

        <tr ng-repeat="book in books">
            <td style="width: 200px">{{book.id}}</td>
            <td style="width: 200px">{{book.name}}</td>
            <td style="width: 50px">{{book.price |currency}}</td>
            <td>
                <button ng-click="removeItem($index)">Удалить</button>
            </td>
        </tr>

        <tr>
            <td></td>
            <td><input type="text" ng-model="name"/></td>
            <td><input type="number" ng-model="price"/></td>
            <td>
                <button ng-click="addBook()">Добавить книгу</button>
            </td>
        </tr>
    </table>

</div>

<script>

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

    App.controller('MyCtrl', function ($scope, $http) {
        $http.get('http://ang:8888/index.php?r=site/api2').success(function (data) {
            $scope.books = data;
        });


        $scope.removeItem = function (index) {
            var id = $scope.books[index].id;
            $scope.books.splice(index, 1);
            $http.post('http://ang:8888/index.php?r=site/del2', {id: id});

        }




        $scope.addBook = function () {
            var newBook = ({name: $scope.name, price: $scope.price});
            $scope.books.push(newBook);

            $http.post("http://ang:8888/index.php?r=site/post2", {name: $scope.name,      price: $scope.price})
                .success(function (data, status, headers, config) {
                    console.log("inserted Successfully");
                });
        $http.get('http://ang:8888/index.php?r=site/api2').success(function (data) {
            $scope.books = data;
        });

        }
    })

问题是由于所有远程调用的异步性质。 您依次调用post和get方法,而没有意识到两者实际上是同步的。 因此,您的帖子后立即有get。

将发布代码更改为

  $http.post("http://ang:8888/index.php?r=site/post2", {
          name: $scope.name,
          price: $scope.price
      }).success(function (data, status, headers, config) {
          console.log("inserted Successfully");
          $http.get('http://ang:8888/index.php?r=site/api2').success(function (data) {
              $scope.books = data;
          });
      });

在上面的代码中,只有在发布完成后才能获取。

暂无
暂无

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

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