0

I'm using 2 different controllers sharing a global value currentOpenningFolder. I want that 2 controllers can both sync to that variable no matter what. But in this example, in the GET request I change the variable in the first controller but I can't view that variable in the second controller. Instead it shows the initial value of currentOpenningFolder. Any ideas why this may be happening?

      angular.module('scopeExample', [])   
.controller('MyController', ['$scope','currentOpenningFolder','$http', function($scope,currentOpenningFolder,$http) {
            $scope.sayHello = function() {

          $http.get('https://api.github.com/users/chuson1996').then(function(obj){
            currentOpenningFolder = obj;
            console.log(currentOpenningFolder);
          })
        };
      }])
      .controller('MyController2', ['$scope','currentOpenningFolder', function($scope,currentOpenningFolder) {
        $scope.sayHello = function() {
          $scope.currentOpenningFolder = currentOpenningFolder;
          console.log($scope.currentOpenningFolder);
        };
      }])
      .value('currentOpenningFolder',{});

2 Answers 2

1

Don't assign an object to other object like this:

currentOpenningFolder = obj;

if you assign as this,currentOpenningFolder will loose reference to original object and refer to other object obj. so best way to do this is to create a property of currentOpenningFolder and assign object to that prperty like this :

currentOpenningFolder.prop = obj;

and then access this to other controller like:

$scope.currentOpenningFolder = currentOpenningFolder.prop;

Edited:

Try this plunkr

Sign up to request clarification or add additional context in comments.

1 Comment

could you please create plunkr or fiddle ?
0

A very simple fix is to extend the existing object instead of replacing it. Replacing it is causing references to be broken

Change

currentOpenningFolder = obj;

To

angular.extend(currentOpenningFolder , obj);

This leaves the existing object intact ( and the other references) and merges changes into it.

Also in the controllers I'm not sure why you set the scope variable that points to currentOpenningFolder within a function. You likely want to declare it outside the function

Without seeing more code it seems like $scope.sayHello=function(... should be replaced with $scope.currentOpenningFolder = currentOpenningFolder;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.