0

I have a variable that i use almost everywhere in my app, in many different controllers. I'm looking for the best possible way of setting that variable knowing that :

-The variable will need to get updated from a controller and resulting in an update on the whole app ( other controllers mainly).

-Some of those function are instance of an object with function in itself that have a callback , does that cause any issue?

So far there seems to be 2 way of doing that : rootScope but that rarely advised apparently:

myApp.run(function ($rootScope) {
   $rootScope.var = "string";
});

And building a custom directive ( but what about setting it's variable ?)

angular.module('myApp').factory('test', function() {
 return {
     test : 'string'
  };
});

Can anyone point me in the right direction and help me choose betweem the two?

1 Answer 1

1

I would recommend using a service or factory save that value in someService.variable and the broadcast n event that this value has been changed. I am attaching sample code. It may contain some syntactical error but I want to give you an idea

  angular.module("myapp")
  .controller('myCtrl', function($scope, $rootScope, myService) {
    $scope.change = function() {
      myService.var = 'abc';
      $rootScope.broadcast('varChanged');
    };
  })

.controller('myOtherCtrl', function($scope, $rootScope, myService) {

    $rootScope.on('varChanged', function(e) {
      use(myService.var);
    });
  })
  .service('mySerice', function() {
    this.var = '';

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

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.