title: Running AngularJS initialization code when view is loaded
body: <p>When I load a view, I'd like to run some initialization code in its associated controller.</p>
  
  <p>To do so, I've used the ng-init directive on the main element of my view:</p>
  
  <pre><code>&lt;div ng-init="init()"&gt;
    blah
  &lt;/div&gt;
  </code></pre>
  
  <p>and in the controller:</p>
  
  <pre><code>$scope.init = function () {
      if ($routeParams.Id) {
          //get an existing object
          });
      } else {
         //create a new object
      }
  
      $scope.isSaving = false;
  }
  </code></pre>
  
  <p>First question: is this the right way to do it? </p>
  
  <p>Next thing, I have a problem with the sequence of events taking place. In the view I have a 'save' button, which uses the <code>ng-disabled</code> directive as such:</p>
  
  <pre><code>&lt;button ng-click="save()" ng-disabled="isClean()"&gt;Save&lt;/button&gt;
  </code></pre>
  
  <p>the <code>isClean()</code> function is defined in the controller:</p>
  
  <pre><code>$scope.isClean = function () {
      return $scope.hasChanges() &amp;&amp; !$scope.isSaving;
  }
  </code></pre>
  
  <p>As you can see, it uses the <code>$scope.isSaving</code> flag, which was initialized in the <code>init()</code> function.</p>
  
  <p>PROBLEM: when the view is loaded, the isClean function is called <strong>before</strong> the <code>init()</code> function, hence the flag <code>isSaving</code> is <code>undefined</code>. What can I do to prevent that?</p>