Beginning AngularJS

(WallPaper) #1

Chapter 3 ■ IntroduCtIon to MVC


Listing 3-2. MVC in Action


function MyFirstCtrl($scope) {


// populate the employees variable with some model data
var employees = ['Christopher Grant', 'Monica Grant', 'Christopher Grant', 'Jennifer
Grant'];


// Now put this model data into the scope so it can be used in the view
$scope.ourEmployees = employees;
}


Review Listing 3-2. We assign the model data to the ourEmployees property that we set on this $scope object.
This is the answer: this is how the model data, the employees array, finds its way into the view. The $scope object was
supplied to our controller function by the AngularJS framework, and all that we needed to do was to populate it with
the data that we wanted to make available to the view.
Glance back at the view in Listing 3-2, and notice that the expression uses a reference to ourEmployees. You can
think of this expression {{ourEmployees.length}} as effectively being the same thing as {{$scope.ourEmployees.
length}}. Don’t actually use a scope reference in this manner within an expression; it won’t work, as the use of the
current scope object is implicit.
Listing 3-3 pulls all of this together into a single MVC example. It’s short and simple, but the essence of AngularJS
is on display here.


Listing 3-3. A Complete MVC Example


<!DOCTYPE html>








Number of Employees: {{ ourEmployees.length}}



Free download pdf