javascript - AngularJS : How to make my Controller variable available on all page context? -
i work angularjs. in 1 of view controller, initialize 1 of variable recipesdata. here 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 make variable recipesdata global. have external script expects variable initialized.
<script src="https://myexternal/lib/js/script.js"></script>
how make global or make available script imported on head ? variable initialized controller.
thanks
you can using rootscope
, using service
, best solution using service
. here sample service code, make service according 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 service. taskservice.addtask($scope.data); // service in controller adding taskservice. taskservice.gettask(); }
this service per 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 example helpful you.
Comments
Post a Comment