Angular store value to service to acces on multiple pages

試著忘記壹切 提交于 2019-12-06 09:18:38

You're not far from the solution.

Seriously, I used to try to remember the difference between service and factory. In the end, both can be used exactly in the same way, to fulfill the same requirement.

app.factory('dmFactory', function() {
//name.value should equal to system.value from the controller 
var somethingIWantToRemember = {};
return {
   set: set,
   get: get
}

function get(key){      //You can forget about the key if you want
    return somethingIWantToRemember[key];
}

function set(key, value){
    somethingIWantToRemember[key] = value;
}

});

and in your controller, you just have to call both functions that way :

$scope.something = dmFactory.get(key);

or

dmFactory.set(key, $scope.something);

From your controller, if your reset it when page load, it is normal that your data gets reseted.

You need to : - inject your service into your controller

app.controller('myCtrl',['myService',function(myService){
  
  }]);
  • create a get function from your service to retreive the value of the variable

factory.getVal = function(){
  return val;  
};
  • call the get function at start of your controller as

$scope.isActiveSystem = myService.getVal();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!