AngularJS - Services, Services

by derkoe

HTML

<script src="http://code.angularjs.org/1.1.4/angular.js"></script>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css">
<div ng-app="myapp">
    <fieldset ng-controller="FirstCtrl">
        <legend>FirstCtrl ({{ fullName() }})</legend>
        <input type="text" ng-model="data.person.first">
        <input type="text" ng-model="data.person.last">
    </fieldset>
</div>

JavaScript

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

myapp.factory('personService', function ($http) {
    var personService = {
        data : { person : null },
        fullName : function () { 
            if(this.data.person) {
                return this.data.person.first + ' ' + this.data.person.last;
            } else {
                return null;
            }
        }
    };

    $http.get('/echo/jsonp/?first=Chris&last=TestLast')
        .success(function(data) { 
            personService.data.person = data;
        });
 
    return personService;
});

myapp.controller('FirstCtrl', function ($scope, personService) {
    $scope.data = personService.data;
    $scope.fullName = personService.fullName;
});