Using Controllers and Scopes with AngularJS: Using Scope-less Controllers

If scopes seem unnecessarily complex and your application doesn’t benefit from inheritance or need to communicate between controllers, then you can use scope-less controllers. These are controllers that provide data and behaviors to views without using scopes at all. Instead, the view is provided with a special variable that represents the controller, as shown in Listing 13-14.

Listing 13-14. Using a Scope-less Controller in the controllers.html File

<!DOCTYPE html>

<html ng-app=”exampleApp”>

<head>

<title>Controllers</title>

<script src=”angular.js”></script>

<link href=”bootstrap.css” rel=”stylesheet” />

<link href=”bootstrap-theme.css” rel=”stylesheet” />

<script>

var app = angular.module(“exampleApp”, [])

.controller(“simpleCtrl”, function () {

this.dataValue = “Hello, Adam”;

this.reverseText = function () {

this.dataValue = this.dataValue.split(“”).reverse().join(“”);

}

});

</script>

</head>

<body>

<div class=”well” ng-controller=”simpleCtrl as ctrl”>

<h4>Top Level Controller</h4>

<div class=”input-group”>

<span class=”input-group-btn”>

<button class=”btn btn-default” type=”button”

ng-click=”ctrl.reverseText()”>Reverse</button>

</span>

<input class=”form-control” ng-model=”ctrl.dataValue”>

</div>

</div>

</body>

</html>

The controller in this example doesn’t declare a dependency on $scope and defines its data values and behaviors using the JavaScript this keyword, as follows:

this.dataValue = “Hello, Adam”;

When applying a scope-less controller, the expression used for the ng-controller directive takes a different form, specifying the name of a variable by which the controller will be accessible in the view:

<div class=”well” ng-controller=”simpleCtrl as ctrl“>

The format of this expression is <controller to apply> as <variable name>, and this example applies the simpleCtrl controller to the div element and creates a variable called ctrl. I then use the ctrl variable to access the data and behaviors in the view, like this:

<input class=”form-control” ng-model=”ctrl.dataValue”>

Scope-less controllers allow you to avoid the complexities of scopes, but they are a relatively new addition to AngularJS and are not widely used. My advice is to take the time to master the way that scopes operate so that you can take full advantage of the features that AngularJS offers—not just in terms of working with controllers but also when you create custom directives using the techniques that I describe in Chapters 15-17.

Source: Freeman Adam (2014), Pro AngularJS (Expert’s Voice in Web Development), Apress; 1st ed. edition.

Leave a Reply

Your email address will not be published. Required fields are marked *