Private variables in Factories

by Andrew Golightly

HTML

<script src="http://code.angularjs.org/angular-1.0.0rc9.js"></script>
<script src="&lt;link href=&quot;http://twitter.github.com/bootstrap/assets/css/bootstrap.css&quot; rel=&quot;stylesheet&quot;&gt;"></script>
<div ng-controller="FactoryCtrl">
    
    <input type="number" ng-model="testFactory.number1">
        <p>{{testFactory.number1}}</p>
    <button ng-click="checkValues()">Check values</button>
            <button ng-click="showValue()">Show number1</button>
</div>

JavaScript

//angular.js example for factory vs service
var app = angular.module('myApp', []);
    
app.factory('testFactory', function(){
    var number1 = 0, number2 = 0;
    
    var printValues = function() {
      
        console.log('number1: ' + number1);             
        console.log('number2: ' + number2);
    };
    
    return {
        number1 : number1,
        printValues: printValues
    };               
});

function FactoryCtrl($scope, testFactory)
{
    $scope.testFactory = testFactory;
    
    $scope.checkValues = function() {
      
        $scope.testFactory.printValues();
        
    };
    
    $scope.showValue = function() {
    console.log('number1: ' + $scope.testFactory.number1);
            console.log('number1 (from factory): ' + testFactory.number1);
    };
}