简体   繁体   English

AngularJS不更新视图

[英]AngularJS doesn't update view

I've a problem with AngularJS. 我对AngularJS有个问题。 It doesn't update view if I edit data on JSON file. 如果我在JSON文件上编辑数据,它不会更新视图。 I've tried to do in this manner too "$scope.loadData = function() {}" but it doesn't change anything! 我试图以这种方式做“$ scope.loadData = function(){}”,但它没有改变任何东西!
Thank you before for the help. 谢谢你的帮助。

HTML Code HTML代码

<!doctype html>
    <html ng-app>
      <head>
        <title>JavaScript &amp; jQuery - Chapter 9: APIs - Angular with remote data</title>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script>
        <script src="js/angular-external-data.js"></script>
        <link rel="stylesheet" href="css/c09.css">
      </head>
      <body>
        <header><h1>THE MAKER BUS</h1></header>
        <h2>Session Times</h2>
        <div class="third"><img src="img/toys1.jpg" alt="Circuit boards" /></div>
        <div class="two-thirds" id="timetable">
          <table ng-controller="TimetableCtrl">
            <tr><th>time</th><th>title</th><th>detail</th></tr>
            <tr ng-repeat="session in sessions">
              <td>{{ session.time }}</td>
              <td>{{ session.title }}</td>
              <td>{{ session.detail }}</td>
            </tr>
          </table>
        </div>
      </body>
    </html>

AngularJS Code AngularJS代码

function TimetableCtrl($scope, $http) {
    $http.get('js/items.json')
        .success(function(data) {$scope.sessions = data.sessions;})
        .error(function(data) {console.log('error');});
}

JSON data JSON数据

{
    "sessions": [
       {
            "time": "09.00",
            "title": "Intro to 3D Modeling",
            "detail": "Come learn how to create 3D models of parts you can then make on our bus! You'll get to know the same 3D modeling software that is used worldwide in professional settings like engineering, product design, and more. Develop and test ideas in a fun and informative session hosted by Bella Stone, professional roboticist."
        },
        {
            "time": "10.00",
            "title": "Circuit Hacking",
            "detail": "Head to the Electro-Tent for a free introductory soldering lesson. There will be electronics kits on hand for those who wish to make things, and experienced hackers and engineers around to answer all your questions. Feel free to bring your own projects to work on if you have them! Run by Luke Seyfort, elite hacker and The Maker Bus' official lab monitor."
        },
        {
            "time": "11.30",
            "title": "Arduino Antics",
            "detail": "Learn how to program and use an Arduino! This easy-to-learn open source microcontroller board takes all sorts of sensor inputs, follows user-generated programs, and outputs data and power. Arduinos are commonly used in robotics, mechatronics, and all manners of electronics projects around the world. Taught by Elsie Denney, professional software developer with a long previous career as a technical artist in the video game industry, electronics enthusiast and instructor."
        },
        {
            "time": "13.00",
            "title": "The Printed Lunch",
            "detail": "Discover and taste the brave new world of the printed lunch. You will not only get to see how 3D printers are being used to recreate traditional foods, but also see entirely new types of treats being made. Will you be the visitor that we create a chocolate model of?"
        },
        {
            "time": "14.00",
            "title": "Droning On",
            "detail": "We have ways of keeping you awake after lunch. This session will be policed by a set of quadcopters remotely controlled via many different types of sensor hooked up to an Arduino board. Snoozing could result in a visit from the drones..."
        },
        {
            "time": "15.00",
            "title": "Brain Hacking",
            "detail": "With advances in affordable electro-encephalography, measuring brain waves is something accessible to everyone. Celebrated neuroscientist Cino Rylands will be inviting the audience to participate in creating a symphony of the mind."
        },
        {
            "time": "16.30",
            "title": "Make The Future",
            "detail": "See how the next generation of makers can be inspired to create a new future for themselves. Learn all about the different tools we can use to enlighten and encourage others to get on board the bus!"
        }
    ]
}

If you change the file on your server your client will not know about that change. 如果您更改服务器上的文件,您的客户端将不知道该更改。

Things you can do: 你可以做的事情:

  • Use a websocket to notify the client he needs to reload that json file (You'l need server side support) 使用websocket通知客户端他需要重新加载该json文件(您需要服务器端支持)
  • Use polling by interval to sample the file and reload it (Simpler) 按间隔使用轮询对文件进行采样并重新加载(更简单)

For instance, simple polling by 1 second interval: 例如,简单的轮询间隔为1秒:

var app = angular.module('myApp');

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

    var nextPolling;
    var pollingInterval = 1000; // 1 second
    var _polling = function ()
    {
        $http.get('js/items.json')
            .success(function(data) {$scope.sessions = data.sessions;})
            .error(function(data) {console.log('error');})
            .finally(function(){ nextPolling = $timeout(_polling, pollingInterval); });
    };

    _polling();

    $scope.$on('$destroy', function (){
        if (nextPolling){
            $timeout.cancel(nextPolling);
        }
    });

});

It's a promise so it sets $scope.sessions after it returns. 这是一个承诺,所以它在返回后设置$ scope.sessions。

Change like this, 像这样改变,

app.controller("TimetableCtrl", ["$scope","$http",
    function($scope, $http) {
             $http.get('test.json').then(function (response){
                $scope.sessions = response.data.sessions;
        });

}]);

Working App 工作App

You are using $scope which is not recommendable as described in this article by John Pappas. 您正在使用$scope中的说明是不推荐文章由约翰·帕帕斯。 Change it to use the controller instance, so your code will look like the example below: 将其更改为使用控制器实例,因此您的代码将如下所示:

Javascript: 使用Javascript:

function TimetableCtrl($scope, $http) {
      var vm = this;
      $http.get('js/items.json')
        .success(function(data) {vm.sessions = data.sessions;})
        .error(function(data) {console.log('error');});
}

HTML: HTML:

<table ng-controller="TimetableCtrl as vm">
        <tr><th>time</th><th>title</th><th>detail</th></tr>
        <tr ng-repeat="session in vm.sessions">
          <td>{{ session.time }}</td>
          <td>{{ session.title }}</td>
          <td>{{ session.detail }}</td>
        </tr>
      </table>

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

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