Thursday, January 15, 2015

The Brains of the Operation: The Controller

With a handle on the model and the view, we move onto the linchpin of the app; the controller. At the core, the controller code is focused on:
  • Obtaining information from the model and passing it to the view.
  • Obtaining user interactions from the view and passing it onto the model. 
While there are a number of different JavaScript MVC frameworks, I settled on AngularJS <https://angularjs.org/> for the following reasons:
  • It is gaining popularity.
  • It is easy to use.
  • It is owned by Google.
AngularJS provides an excellent tutorial <https://docs.angularjs.org/tutorial> that will get one up to speed sufficient to understand what comes next in this series of posts.  I will refer back to parts of this tutorial through the remaining posts.

UPDATE 1/22/15: Another excellent tutorial that is now being promoted by Angular.js is <http://angular.codeschool.com/>.  It is a video tutorial that is excellent.

From an earlier post, we start with a most basic AngularJS application in JSFIDDLE. Because we want to now use a fairly recent version of AngularJS, we will use the version provided by a Google CDN
<//ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js> by adding it to the "External Resources" rather than the older version available in JSFIDDLE.

note: It is important to set the place the JavaScript included in the HTML as "No wrap - in <head>".

In order to make sense of the following starting point, one will need to make it through step 5 in the tutorial: XHRs & Dependency Injection <https://docs.angularjs.org/tutorial/step_05>.

HTML
<div ng-app="myApp">
    <div ng-controller="myCntrl">
       {{test}}
    </div>
</div>

JavaScript
var myApp = angular.module('myApp', []);
myApp.controller('myCntrl', ['$scope', function($scope) {
   $scope.test = 'hello world';
}]);

No comments:

Post a Comment