Angular 01 - Module Service examples

by Sky Sigal

HTML

<div data-ng-app="App1">
    <div data-ng-controller="SomeParentCtrl">
        <div data-ng-controller="SomeCtrl">
            <b>Scalar Binding:</b><br/>
            <div>Number:<span data-ng-bind="someNumber"/></div>
            <div>Text:<span data-ng-bind="someText"/></div>
            <!-- to object properties -->
            <div>First:<input data-ng-model="someObject.first"/></div>
            <!-- to behaviour -->
            <div>Last:<span data-ng-bind="someObject.full()"/></div>
       </div>
    </div>
</div>

JavaScript

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

//ABOUT:
//We've already covered Constants, Values, Factories.
//A Service is a Singleton class:

//note how '$scope' is mapped to $sc: and 'foo' is DI'ed value:
app1.controller('SomeParentCtrl', ['$scope', 'foo', function ($sc, foo) {
    $sc.someText = foo;
}]);
app1.controller('SomeCtrl', ['$scope', 'barService', function ($scope, barService) {    
    $scope.someNumber = barService.func2();
    $scope.someObject = {
        first : 'John',
        last : 'Smith',
        full : function(){return this.first + ' ' + this.last;}
    };    
}]);
//NOTICE: 
//Define a value, that will be injected into the controllers:
//Note that it works even if defined later, as long as it is defined
//before controller is constructed:
app1.constant("foo", "fooey");


app1.service("barService", ['foo', function (foo){
    this.func1=function() {return "blah";}
    this.func2=function() {return "blah...." + foo;}
}]);