简体   繁体   中英

Value set from one controller into service to be used on another controller returns no value on page refresh using angular js(new to angular)

I have a HTML code

<div id="{{item.codeName}}">
    <a class="search-results" href="" ui-sref="app.location" ng-click="vm.setValue(item._id)">{{item.codeName}} </a><br><br>
</div>

on ng-click from the controller i'm invoking a function vm.setValue by passing id to controller1 where i am passing id value to the service to set.

In Controller1

 vm.setValue = function(Id){
            service.setId(Id);
    }

My Service

angular.module('myApp', [])
.service('setProperties', function () {
    var _Id = null;
        function getId(){
    return _Id; 
}
function setId(Id){
    _Id = Id;
  }
});

I was successful setting the _Id into service and getting the Id value into my another controller at once...

In controller2

 vm.loadDealDetails = function () {      
setProperties.loadSearchDealDetails(setProperties.getId()).then(function(data) {
            if (data !== null) {  
                vm.dealDetailData.push(data);
                setProperties.setId(vm.dealDetailData._id);
            }
        });
    }

In controller2 i'm invoking function vm.loadDealDetails on page load where i am getting a data from another function of service loadSearchDealDetails by passing id value from getId function of service...again from the data response i get the Id value and i am setting it into service...but this works only once in a process

As i load/refresh page function vm.loadDealDetails function is invoked but im not getting any value by this setProperties.getId() as it goes empty without response....how would i make getId working on page load/refresh also Please Help

You are not getting the value because when you reload your app, your app is loaded again and so js files are reloaded as well. So, its as good as fresh app.

Now, you can do below things to keep hold of the data:

  1. Assign value to localStorage . Check this link and implement using angularJS way.
  2. Use server session to retain the data even after app reload.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM