Pracede Pracede - 3 years ago 97
AngularJS Question

AngularJS : How to make my Controller variable available on all page context?

I work with angularjs. In one of my view controller, i initialize one of my variable recipesData.
Here is the controller :

(function() {
'use strict';

angular
.module('myApp')
.controller('CookController', CookController);

CookController.$inject = ['$document','$scope','$rootScope','$window'];

function CookController ($document,$scope,$rootScope,$window) {

var vm = this;


var recipesData = load();


var viewer, ui, building;

$scope.load = function () {
var data;
// create data
// ..........
return data;
};

};

})();


I want to make my variable recipesData global. I have an external script which expects this variable initialized.

<script src="https://myexternal/lib/js/script.js"></script>


How to make it global or make it available from script imported on head ? My variable is initialized from my controller.

Thanks

Answer Source

you can do this using rootscope and using service , but best solution is using a service. Here is sample service code, make your service according to your requirement.

 fcty.service('taskService', function() {
    var task = {};
    var addTask = function(newObj) {
        task = newObj;
    }

    var getTask = function() {
        return task;
    }
    return {
        addTask: addTask,
        getTask: getTask,
    };
});

add taskService in controller

cntrl.controller('taskCreateController', function($scope, $http,taskService) {

// Add to service.

taskService.addTask($scope.data);

// Get from service in any controller by adding taskservice.

taskService.getTask();


}

This service is as per your requirement.

var app = angular.module('myApp', []);

app.service('recipeService', function() {
    var recipeData = {};
     var addRecipe = function(newObj) {
        recipeData = newObj;
    }

    var getRecipe = function() {
        return recipeData;
    }
 return {
        addRecipe: addRecipe,
        getRecipe: getRecipe,
    };

});


app.controller('CookController', function($scope, $http, recipeService) {

  var vm = this;
  var viewer, ui, building;

        $scope.load = function ()  {
           var data;
           // create data 
           // ..........
            recipeService.addRecipe(data);
            return data;
        };

});

Hope this example is helpful to you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download