1

States declared like this. As you can see there is a state called "market" with a sub-state called "list". They share the controller, but have different templates.

.state('market', {
            url: '/market',
            templateUrl: '/market',
            controller: 'MarketController',
            access: { requiredLogin: true }
        }).state('market.list', {
            url: '/list',
            templateUrl: '/market/list',
            controller: 'MarketController',
            access: { requiredLogin: true }
        })

In the controller I have declared a variable, $scope.activeProduct, whose value can be modified by clicking on a button in the "market.*".

I have placed {{activeProduct}} in both of the templates. When the button is clicked, the value only changes in the "market.*" part.

This is the function that is triggered upon clicking the button:

        $scope.switchProduct = function (id) {
        $timeout(function() {
            $scope.$apply(function(){
                    $scope.activeProduct = id;
                    MarketStorageService.activeProduct = id;
                    console.log("activeproduct changed to" + id);
                }
            );
        });
    };

I just don't understand why in the "market.list" the value does not change.

Markus Pint
  • 348
  • 3
  • 17

1 Answers1

2

This is the common gotcha of scope inheritance in angular. The child state's scope has its own copy of activeProduct, and so when it changes the inheritance chain is not consulted about the change. This is all explained pretty well in What are the nuances of scope prototypal / prototypical inheritance in AngularJS?. A quick fix would be to reference the variable on the parent scope:

$scope.$parent.activeProduct;

In the child state.

Community
  • 1
  • 1
Mohammad Sepahvand
  • 17,364
  • 22
  • 81
  • 122