Angularjs - loading data using a service displays the previous page data and not the current one
<p>I'm facing a strange behaviour on my angularjs app.</p>
<p>Basically, I have a service that loads data from a JSON file.</p>
<p>I have two options from this service:</p>
<blockquote>
<p>1- Load all the data</p>
<p>2- Load only the data that I need based on the URL</p>
</blockquote>
<p>Here's the service code:</p>
<pre><code>.service ('myService', ['$http', '$stateParams', '$q', function ($http, $stateParams, $q){
  
  var myService = this;
  var defer = $q.defer();
  
  myService.all = {};
  myService.one = {};
  
  myService.all = function (){
    $http.get('data.json').success(function (res){
      myService.all = res.data;
      defer.resolve(res.data)
    })
    return defer.promise;
  } 
  myService.one = function (urlID){
    $http.get('data.json').success(function(res) {
      angular.forEach(res.data, function(item) {
        console.log (item, parseInt(urlID))
        if (item.id === parseInt(urlID)) {
          console.log(&quot;id equality: true&quot;)
           myService.oneZone = item;
        } else {console.log(&quot;id equality: false&quot;)}
        
      });
    });
    return defer.promise
  }
  
  return myService;  
}])
</code></pre>
<p>and then I call this from my controller:</p>
<pre><code>.controller('detailsCtrl', ['$scope', '$stateParams', 'myService', function($scope, $stateParams, myService) {
    $scope.fromURL = $stateParams.myID
    myService.one($scope.fromURL).then(function(res){
      $scope.onlyOne = myService.oneZone
    })    
}])
</code></pre>
<p>but the data is displayed in a wrong way.</p>
<p>It is way easier to see it in action here: <a href="https://plnkr.co/edit/qBtT5gkVSkYfjbngZVqw?p=preview" rel="nofollow noreferrer">https://plnkr.co/edit/qBtT5gkVSkYfjbngZVqw?p=preview</a></p>
<p>To reproduce this, here's what you have to do:</p>
<blockquote>
<p>1- Once open, click on any button (for example <strong>2</strong>)</p>
<p>2- the following page will have an empty scope (called onlyOne)</p>
<p>3- Go back and click on another button (for example <strong>3</strong>)</p>
<p>4- onlyOne scope is from the first button you pressed (<strong>2</strong>)</p>
</blockquote>
<p>why is it doing this?</p>
<p>thanks</p>