Scopes

by jamey777

HTML

<script src="http://code.angularjs.org/angular-1.0.0rc9.js"></script>
<div ng-controller="DefaultCtrl">
    <div>
        <h2>$scope.originalSettings values<h2>
            <div>faveColor: <input ng-model="originalSettings.faveColor"></input>  {{originalSettings.faveColor}}</div>
            <div>loggedIn: {{originalSettings.loggedIn}}</div>
            <div>timestamp: {{originalSettings.timestamp}}</div>
    </div>
            <br>
                <div>
        <h2>$scope.copyOfSettings values<h2>
            <div>faveColor:  <input ng-model="copyOfSettings.faveColor"></input>{{copyOfSettings.faveColor}}</div>
            <div>loggedIn: {{copyOfSettings.loggedIn}}</div>
            <div>timestamp: {{copyOfSettings.timestamp}}</div>
    </div>
            <button ng-click="checkService()">check service values</button>
</div><br><br>
            <div ng-controller="OtherCtrl">
    <div>
        <h2>$scope.originalSettings values<h2>
            <div>faveColor: {{originalSettings.faveColor}}</div>
            <div>loggedIn: {{originalSettings.loggedIn}}</div>
            <div>timestamp: {{originalSettings.timestamp}}</div>
    </div>
            <br>
                <div>
        <h2>$scope.copyOfSettings values<h2>
            <div>faveColor: {{copyOfSettings.faveColor}}</div>
            <div>loggedIn: {{copyOfSettings.loggedIn}}</div>
            <div>timestamp: {{copyOfSettings.timestamp}}</div>
    </div>
            <button ng-click="checkService()">check service values</button>
</div>

JavaScript

var app = angular.module('myApp', []);


app.service('testService', function($http) {
    var that = this;
    this.settings = {
        faveColor: 'green',
        loggedIn: true,
        timestamp: new Date()
    };

    this.checkValues = function() {
        return that.settings.faveColor + ', ' + that.settings.loggedIn + ', ' + that.settings.timestamp;
    };

});

function DefaultCtrl($scope, $rootScope, testService) {
    $scope.originalSettings = testService.settings;
    $scope.originalSettings.faveColor = 'greenish';

    $scope.copyOfSettings = angular.copy(testService.settings);
    $scope.copyOfSettings.faveColor = 'blue';

    $scope.checkService = function() {
        console.log('service values are: ' + testService.checkValues());
    }
}

function OtherCtrl($scope, $rootScope, testService) {
    $scope.originalSettings = testService.settings;
    $scope.originalSettings.faveColor = 'other greenish';

    $scope.copyOfSettings = angular.copy(testService.settings);
    $scope.copyOfSettings.faveColor = 'other copy blue';

    $scope.checkService = function() {
        console.log('service values are: ' + testService.checkValues());
    }
}