Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS ng-include do HistoryJS stop working

My code was working until I started using ng-include. Now, everytime I'll go to a page that uses this directive, I'm getting stuck on the page. The back button has stopped working and you stay forever in a loop of the same page.

My website is running with Asp.NET MVC 5.

Some bits of my code:

HTML "host"

<div id="place">
    <div data-ng-include="'/app/angular/views/place.html'"></div>
</div>

HTML place.html

<div>
    <h1>{{place.PlaceName}}</h1>
    <ul class="unstyled-list">
        <li data-ng-repeat="hint in place.Hints">
            <!-- more code -->
        </li>
    </ul>
</div>

JAVASCRIPT

$scope.place = { };

// 'maps' is a google maps plugin 
maps.autoComplete({ success: function(result) {
    // gets the result of the user search
    History.pushState({ name: result.name, id: result.id }, result.name, '/place/' + result.id);
});

History.Adapter.bind(window, 'statechange', function () { 
    var state = History.getState(); 

    // go to the server and get more info about the location
    $mapService.getMetaInfo({id: state.data.id}).then(function (d) {
        // get place info
        $scope.place = d;
    });
});

When I remove the ng-include and replace it with the "raw" html, it works fine. This "infinite loop" happens only when ng-include is added.

like image 267
Le Coder Avatar asked Jan 16 '14 11:01

Le Coder


1 Answers

When you set template url inside ng-include directive, the specified template get called by angular then it put it in angular $templateCache and then that content gets render on the view. If you call it next time it directly gets fetched from angular $templateCache. I would prefer you to put that template in templateCache in angular run phase (before angular run it compile cycle.) I would suggest you to load that template in at the start up of angular.

Put this template inside your angular $templateCache before loading angular on the page(i.e. right after angular config phase)

CODE

angular.module('app',[]).
config(function(){
  //configuration code will be here.
}).
run(function($templateCache,$http){
  //run block will run write after the config phase
  $http.get('/app/angular/views/place.html',{ cache : $templateCache }
});

After this template will be available from $templateCache without making any ajax for template.

Hope this will not cause any infinite loop. like you are facing problem currently.

Thanks.

like image 177
Pankaj Parkar Avatar answered Sep 28 '22 12:09

Pankaj Parkar