Jahongir Rahmonov
Jahongir Rahmonov

Reputation: 13753

$location.path is changing the scope of the Controller

I have this ngDialog modal:

$scope.showMessage = function(size, status, data) {
    // open modal page
    ngDialog.open({
        scope: $scope,
        template: 'orderResponse.html',
        controller: $controller('OrderResponseModalController', {
            $scope: $scope,
            responseStatus: status,
            responseData: data
        }),
        className: 'createGroup',
        closeByDocument: false,
        closeByEscape: false
    });
};

So, basically, it will open a modal for which OrderResponseModalController will be responsible, and it sends to this controller three values.

There is this code inside this controller:

$scope.message = responseData.message;
$scope.title = responseData.title;
...
$location.path("purchases");

orderResponse.html looks something like this:

<p>{{ message }}</p>
<h1>{{ title }}</h1>

However, the values of these variables are not shown in the browser(just {{message}}). I think it is because $location.path is also changing the Controller $scope.

Is there any way to fix this?

Upvotes: 0

Views: 950

Answers (1)

Bricktop
Bricktop

Reputation: 1549

I am not 100% sure, but controllers are not singletons. This means that everytime you change your location with $location.path("something") a new instance of your controller will be invoked. This means that all scope variables set in that controller beforehand will be lost.

In order to share variables between instances of controllers you should use a service, because services are singletons.

Here is an example I used:

angular.module('angularApp')
.service('sharedProperties', function () {
    var uniEdit = 0;

    return {
        getUni: function () {
            return uniEdit;
        },
        setUni: function(value) {
            uniEdit = value;
        }
    };
});

Upvotes: 2

Related Questions