title: In AngularJs why does one scope variable update when changed, and another very similar variable does not?
body: <p>I have an <code>ItemsService</code> that supplies an array of items to a pair of controllers/views. </p>
  
  <p>In the first case (list view) a change in one of the items in the service results in a change in the UI - all good. </p>
  
  <p>In the second case (detail view) the items binds fine but it does not update if the item changes in the service. </p>
  
  <p>What have I missed?</p>
  
  <p>Plunker: <a href="http://plnkr.co/edit/Jlk2xFfry4N8Wqfw31Em?p=preview" rel="nofollow">http://plnkr.co/edit/Jlk2xFfry4N8Wqfw31Em?p=preview</a></p>
  
  <p>Service:</p>
  
  <pre><code>app.factory('ItemsService', function ($rootScope) {
  
      // omitted code to update items - this works fine
  
      var itemsById = [];
      var itemsArray = [];
  
      function updateItems(itemUpdate) {
          itemsById[itemUpdate.Id] = itemUpdate;
  
          while (itemsArray.length &gt; 0) {
              itemsArray.pop();
          }
  
          for (var key in itemsById) {
              itemsArray.push(itemsById[key]);
          };
      }
  
      return {
          items: itemsArray,
          itemsById: itemsById,
      }
  });
  </code></pre>
  
  <p>Controller for listing items:</p>
  
  <pre><code>app.controller('ItemsController', function ($scope, ItemsService) {
      $scope.items = ItemsService.items;
  });
  </code></pre>
  
  <p>List view:</p>
  
  <pre><code>&lt;table class="table" data-ng-controller="ItemsController"&gt;
      &lt;tr data-ng-repeat="item in items"&gt;
          &lt;td&gt;{{item.Name}}&lt;/td&gt;
      &lt;/tr&gt;
  &lt;/table&gt;
  </code></pre>
  
  <p>Controller for the detail view:</p>
  
  <pre><code>//$stateParams is part of Angular UI Routing - this works because the correct item is selected and displayed - it just doesn't update
  app.controller('ItemController', function ($scope, $stateParams, ItemService) {
      $scope.item = ItemService.itemsById[$stateParams.id];
  });
  </code></pre>
  
  <p>Detail view:</p>
  
  <pre><code>&lt;div data-ng-controller="ItemController"&gt;
      {{item.Name}}
  &lt;/div&gt;
  </code></pre>
  
  <p><strong>Edit</strong></p>
  
  <p>If I wrap the call to assign the item in the second case in a function it works:</p>
  
  <pre><code>app.controller('ItemController', function ($scope, $stateParams, ItemService) {
      $scope.item = function () { return ItemService.itemsById[$stateParams.id]; }
  });
  </code></pre>
  
  <p>Detail view:</p>
  
  <pre><code>&lt;div data-ng-controller="ItemController"&gt;
      {{item().Name}}
  &lt;/div&gt;
  </code></pre>
  
  <p>But my understanding is that it's bad practice to bind to function calls like this..</p>