mjavad sh lan
mjavad sh lan

Reputation: 3

Why is pushState disrupted when using ng-include?

When using ng-include, the pushState function is disrupted.

The following is a simple example of this.

<div ng-app="angularApp" ng-controller="angularCtrl">
    <div ng-include="templateUrl"></div>
    <button ng-click="bye()">BYE</button>
</div>

and

let app = angular.module('angularApp', []);
app.controller('angularCtrl', async function ($scope) {
    $scope.templateUrl = '/assets/hi.html';
    $scope.bye = function () {
        $scope.templateUrl = '/assets/bye.html';
        history.pushState({},'','/finish.html')
    };
});

We want to change the body value after pressing the BYE button using ng-include and also change the page address by pushState. This example is part of a larger project that has been simplified here as much as possible.

Note: According to the reviews, the url is changed by pushState but immediately returns its value. It is ignored during the ng-include process.

Upvotes: 0

Views: 72

Answers (1)

Pete BD
Pete BD

Reputation: 10161

Changing the browser location is inherently tricky in AngularJS. It is best to try to use the $location service as much as possible as this understands and works with the $scope digest machinery better.

Try using the following in your app:

let app = angular.module('angularApp', []);
app.config(function ($locationProvider) {
  $locationProvider.html5Mode(true);
});

app.controller('angularCtrl', function ($scope, $timeout, $location) {
    $scope.templateUrl = '/assets/hi.html';
    $scope.bye = function () {
        $scope.templateUrl = '/assets/bye.html';
        $location.url('/finish.html');
    };
});

Note that you will need to provide a base[href] for html5 mode support:

<html lang="en">
<head>
  ...
  <base href="/">
</head>
<body>
  <div ng-app="angularApp" ng-controller="angularCtrl">
    <div ng-include="templateUrl"></div>
    <button ng-click="bye()">BYE</button>
  </div>
</body>
</html>

Upvotes: 0

Related Questions