how to make a global variables in single controller and call function inside factory in Angularjs -


i want make global variable can access in same controller. want data variable should global can access anywhere within controller. code :-

var enterprise = angular.module('enterprisectrl',[]);     enterprise.controller('enterprisecontroller',function($scope,$routeparams,$http,$location,enterprise){      $scope.enterprisesubmit = function(){              $scope.enterprise.sector_id = $scope.enterprise.select_sector.id;              var f = document.getelementbyid('file').files[0],               reader = new filereader();               reader.onloadend = function(e){               var data  = e.target.result;                }               reader.readasbinarystring(f);               var enterprise = enterprise.insert($scope.enterprise,$rootscope.file);                 enterprise.success(function(response){                    if(response.data !=""){                          $location.path('/enterprises');                    }else alert('data not saved.');                 });         };      }); 

and second things when success response after can send $http.post request in enterprise.success function. :-

enterprise.success(function(response){    if(response.data !=""){        $http.post("http://5.17.18.10:3030/api/login",{status:'1'}).success(function (response)            {               console.log(response);            });           $location.path('/enterprises');      }else alert('data not saved.'); 

a controller has scope, defining variable within controller makes accessable everywhere in controller. global variable mean accesable in other controllers aswell. i'm not sure if want have global variable or variable within scope of controller. if want use variable in views (like ng-model) can define variable $scope.data.

you defined var data in function though, if want accessable outside function, should first declare var data in controller , use variable (without re-declaring) in function.

your other question post in successfunction of post, yeah can done. did try before asking? :-) instead of .success() might want use .then(), reference can read this. problem can occur is, posts done asynchonously. might not return data in order want returned. (because code initial post called continue while post executed asynchronously).

i hope answers questions.

update use $rootscope, isn't best practise. best practise store variable in factory or service (as stated in other answers, service way go variables want access in other controllers) , call on variable in success function.


Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -