0

Assuming my application has a variable "globalFruits" that keeps track of all the "Fruits" within my app.

var globalFruits = {}

globalFruits['Pear'] = {name:'Pear', color:'green'}; globalFruits['Apple'] = {name:'Apple', color:'Blue'};

How should this global variable be included in my AngularJS application such that I can have directives or scopes that can call it and check on its state? Or is that not the AngularJS way?

2
  • if it is global, you can call it from angular? Commented Jun 22, 2013 at 16:37
  • I know how to declare it without using angularJS, but I wnated to know if there was some proper convention to do that. Especially when say, I want globalFruits to be able to affect say, certain UI elements on multiple aspects of my page. Commented Jun 22, 2013 at 16:39

2 Answers 2

2

You can define a value for your module :

app.value('globalFruits', {
  Pear: {name:'Pear', color:'green'},
  Apple: {name:'Apple', color:'Blue'}
);

Then, you can inject this value when you want to work with it :

app.controller('MyController', ['$scope', 'globalFruits', function($scope, globalFruits) {
  $scope.globalFruits = globalFruits;
}]);
Sign up to request clarification or add additional context in comments.

Comments

0

There is a $rootScope model which can be used for things like that

app.config(['$rootScope', function ($rootScope) {
    $rootScope.fruits = [
        {name:'Pear', color:'green'},
        {name:'Apple', color:'Blue'}
    ];
}]);

Which you can use as usual in your HTML view:

<ul>
    <li ng-repeat="fruit in fruits">{{ fruit.name }}</li>
</ul>

To debug scope variables in your browser, you may want to install and use AngularJS Batarang extension for Google Chrome.

More info: http://docs.angularjs.org/guide/scope

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.