user3363022 user3363022 - 2 months ago 7
AngularJS Question

I am using AngularJS, I cannot make global variable change as needed

I am messing around with a home project for the moment, and I am using angularJS with Ionic framework. I am very new to angularJS and I am having trouble declaring and updating a global variable to pass between controllers. I have the following global variable declared:

application.value("dataObject",
{
Nor: 33,
Sus: 33,
Mal: 33
});


I then set dataObject.Nor to some other value in my one controller:

application.controller(
"testingCtrl",
function ($scope, $cordovaCamera, dataObject) {
...dataObject.Nor = 45;
...
}
);


Then I want to access this updated dataObject:

application.controller(
"ResultsCtrl",
function ($scope, dataObject) {
... data: [dataObject.Nor,dataObject.Sus,dataObject.Mal],
...
}
);


However, when I do this the dataObject has not updated and just shows me the default values. I do not know what I am doing wrong and would appreciate any help on the subject!

Answer

I recommend against $rootScope or value. I think these are anti-patterns and $rootScope will go away in Angular 2.

Try a service.

application.service('ConfigService', function() {
  var _config = {};

  this.updateConfig = function(c) {
    angular.copy(c, _config);
  }

  this.getConfig = function() {
    return _config;
  }
})

application.controller(
    "testingCtrl",
    function ($cordovaCamera, ConfigService) {
        ConfigService.updateConfig({Nor: 45});
    }
);

application.controller(
    "ResultsCtrl",
    function ($scope, ConfigService) { 
      var dataObject = ConfigService.getConfig();
      var data = [dataObject.Nor,dataObject.Sus,dataObject.Mal],
    }
);

Keep in mind that when the first index of data (dataObject.Nor) will not update with another call to updateConfig. The reason being you are passing a simple datatype where the reference is lost.