Ricardo Agra Ricardo Agra - 1 year ago 133
AngularJS Question

JavaScript Angular 1.5.x Controller

When learning Angular 1.5, I got really confused about the usage of the tags.

Namely, I can't understand why there needs to be a 'global' object to contain the variables within a controller.

JS Bin : http://jsbin.com/puyayocomi/11/edit?html,js,output

The question is : Why can't we call variables directly created within the controller instead of using a global object( in this case called 'namespace' )to hold all the controller variables?

index.html :

<!DOCTYPE html>
<html ng-app="todoApp">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<h2> Angular Controllers </h2>

<!-- Why not : ng-controller="todoCtrl" -->
<div ng-controller="todoCtrl as namespace">
<!-- -->
<ul class="unstyled">
<!-- Why not : ng-repeat="todo in todos" -->
<li ng-repeat="todo in namespace.todos">
<!-- -->
<label class="checkbox">
<input type="checkbox" ng-model="todo.done">
<span class="done-{{todo.done}}">{{todo.text}}. </span>

JavaScript :

console.log( 'Hello Script!' );

angular.module( 'todoApp',[] ).controller( 'todoCtrl',function()
var namespace = this;

namespace.todos =
{ text:'one', done:true },
{ text:'two', done:false }

<!-- Why not : -->

var todos =
{ text:'one', done:true },
{ text:'two', done:false }

Answer Source

It basically comes down to how function scopes work in JavaScript:

function Controller() {
  // local variable
  var foo = 1;

  // instance property
  this.bar = 2;

// imagine Angular creates an instance of your controller like this:
var instance = new Controller();
console.log('foo', instance.foo) // undefined
console.log('bar', instance.bar) // 2

So, in short: Local variables can not be accessed from outside the function, while properties bound to this can.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download