Successfully Call history.pushState() from Angular Without Inifinite Digest?

后端 未结 4 1338
野的像风
野的像风 2021-01-17 16:46

Is there a way to call history.pushState() without angular going into an infinite digest loop?

I\'m trying to migrate my app from backend routing to fro

4条回答
  •  日久生厌
    2021-01-17 16:47

    I was able to come up with a solution that works with angular 1.2.15.

    The gist of it is to add a target attribute to each link and then use the $location service to change the location.

    Based on the current angular code, anchor tags that have a target attribute are ignored (note that this solution may eventually break).

    To do this, ensure this javascript runs before angular:

    // prevent angular from taking over link clicks until we have frontend routing
    $(document.documentElement).on("click","a",function(event) {
      var elem = $(this), target = elem.attr("target");
      if(!target) {
        elem.attr("target","_self");
        setTimeout(function() {
          elem.removeAttr("target");
        });
      }
    });
    

    After that, configure your location provider to use html5mode:

      angular.module("App", ["App.controllers"]).config([
        "$locationProvider", function($locationProvider) {
          if (history.pushState) {
            $locationProvider.html5Mode(true);
          }
        }
      ]);
    

    Now, in your controller, inject the location service and use it normally:

    angular.module("App.controllers",[]).controllers("SomeController", ["$scope", "$location", function($scope,$location){
        $scope.updateLocation = function() {
          if (history.pushState) {
            $location.path("/new/path/here");
          }
        };
      }]);
    

提交回复
热议问题