title: Passing asynchronously obtained data to a directive
body: <p>I currently have an AngularJS <code>controller</code> that is basically getting some <code>JSON</code> asynchronously through a <code>$http.get()</code> call, then linking the obtained data to some scope variable.</p>
  
  <p>A resumed version of the <code>controller</code> code:</p>
  
  <pre><code>mapsControllers.controller('interactionsController', ['$http', function($http) {
    var ctrlModel = this;
  
    $http.get("data/interactionsPages.json").
    success(function(data) {
      ctrlModel.sidebar = {};
      ctrlModel.sidebar.pages = data;
    }).
    error(function() {...});
  }]);
  </code></pre>
  
  <p>Then, I have a custom <code>directive</code> which receives those same scope variables through a <code>HTML</code> element.</p>
  
  <p>A resumed version of the <code>directive</code> code:</p>
  
  <pre><code>mapsDirectives.directive('sidebar', function() {
    return {
      restrict : 'E',
      scope : {
        pages : '@'
      },
      controller : function($scope) {            
        $scope.firstPage = 0;
  
        $scope.lastPage = $scope.pages.length - 1;
  
        $scope.activePage = 0;
  
        //...
      },
      link : function(scope) {
        console.log(scope.pages);
      },
      templateURL : 'sidebar.html'
    }
  });
  </code></pre>
  
  <p>A resumed version of the <code>HTML</code>:</p>
  
  <pre><code>&lt;body&gt;
    &lt;div ng-controller='interactionsController as interactionsCtrl'&gt;
      &lt;mm-sidebar pages='{{interactionsCtrl.ctrlModel.sidebar.pages}}'&gt;
      &lt;/mm-sidebar&gt;
    &lt;/div&gt;
  &lt;/body&gt;
  </code></pre>
  
  <p>The problem is, since the <code>$http.get()</code> is asynchronous, the directive is being badly initialised (e.g: <code>$scope.pages.length - 1</code> is undefined).</p>
  
  <p>I couldn't find anything that solved this problem for me, although there are some presented solutions that would seem to solve the case. Namely, I tried to watch the variables, only initialising the variables after detected changes, as suggested in many other posts. For testing, I used something like:</p>
  
  <pre><code>//... inside the directive's return{ }
  link: function() {
    scope.$watch('pages', function(pages){
      if(pages)
        console.log(pages);
    });
  }
  </code></pre>
  
  <p>I've tested it, and the $watch function wasn't called more than once (the logged value being <code>undefined</code>), which, I assume, means it isn't detecting the change in the variable value. However, I confirmed that the value was being changed.</p>
  
  <p>So, what is the problem here?</p>