简体   繁体   中英

How to reload ng-include in AngularJS?

I'm learning AngularJS by creating a site that interacts with a system I'm writing in node. Part of this site requires that I get info from two different spots (eg the town name from my own database of stored names, plus the weather from another site). I'm using this snippet to get the data:

<tr ng-repeat="town in towns | filter:query | orderBy:orderBy">
    <td ng-bind="town.ShortName"></td>
    <td ng-include src="'http://example.com/weather/' + town.ID'"></td>
</tr>

This works great, as I get the town name (eg Melbourne) and the weather data back. Next, I added socket.io to listen for an event (eg weatherupdate):

  <script type="text/javascript">
    var socket = io.connect();
    socket.on("weatherupdate", function() {
      angular.element("#listController").scope().reloadView()
    })
  </script>

And here's the reload function in my controller:

  $scope.reloadView = function() {
        $route.reload();
  }

That works for the most part. If I make a change to the town ShortName, next time "weatherupdate" is emitted, the view flickers (like it's reloading) and the new town.ShortName is shown in the td .

However, the weather doesn't change. If I manually reload the page (either with F5 or a javascript function to reload the whole page), the new weather is fetched just fine, but when the route is auto-reloaded by the function, everything but ng-include src is updated.

I also tried adding

$templateCache.remove($route.current.templateUrl);

just above $route.reload() but to no avail. I guess I could $http.get the weather data and manipulate it, but I figured ng-include would be nice and easy

Using $templateCache.remove($route.current.templateUrl); will remove the cache for your page, but will not remove the cache for all external request made from that route, so that is not what you want.

You need to either remove the cache for each of the urls that the are ng-included before reload, or you need a way to bypass the cache. An easy way to do this is to add a query param of the time at update to the url like so:

In your list controller:

$scope.updateTime = Date.now();

And in your HTML:

<tr ng-repeat="town in towns | filter:query | orderBy:orderBy">
    <td ng-bind="town.ShortName"></td>
    <td ng-include src="'http://example.com/weather/' + town.ID + '?updated=' + updateTime"></td>
</tr>

While the server will ignore the updated query parameter, any sort of caching will not be applied due to the different url.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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