matsko matsko - 9 months ago 31
AngularJS Question

AngularJS $location not changing the path

I'm having an issue with changing the URL of the page after a form has been submitted.

Here's the flow of my app:

  1. Routes are set, URL is recognized to some form page.

  2. Page loads, controller sets variables, directives are fired.

  3. A special form directive is fired which performs a special form submission using AJAX.

  4. After the AJAX is performed (Angular doesn't take care of the AJAX) then a callback is fired and the directive calls the
    function which sets the location.

The problem is that after setting the location the nothing happens. I've tried setting the location param to
as well... Nope. I've also tried not submitting the form. Nothing works.

I've tested to see if the code reaches the
function (which it does).

My only thought is that somehow the scope of the function is changed (since its called from a directive), but then again how can it call
if the scope changed?

Here's my code

var Ctrl = function($scope, $location, $http) {
$http.get('/resources/' + $ + '/edit.json').success(function(data) {
$scope.resource = data;

$scope.onAfterSubmit = function() {
Ctrl.$inject = ['$scope','$location','$http'];

Can someone help me out please?


I had a similar problem some days ago. In my case the problem was that I changed things with a 3rd party library (jQuery to be precise) and in this case even though calling functions and setting variable works Angular doesn't always recognize that there are changes thus it never digests.

$apply() is used to execute an expression in angular from outside of the angular framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).

Try to use $scope.$apply() right after you have changed the location and called replace() to let Angular know that things have changed.