Binding Via Function

Exploring ways to update bindings when a shared service changes.

by Thomas Burleson

HTML

<script src="http://code.angularjs.org/1.0.1/angular-1.0.1.js"></script>
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<h3>Exploring `shared` data models and databinding in AngularJS</h3>

<br/>

<div ng-controller="ControllerZero">
    <input ng-model="text" >
    <button ng-click="onAgeChange(text);">UPDATE AGE</button>
    <button ng-click="onUserNameChange(text);">UPDATE USER.NAME</button>
</div>
<hr />
<h3>Controller One</h3>
<div ng-controller="ControllerOne">
    <p>Via Get Function: {{ ageFn() }}</p>
    <p>Via Assignment: {{ user.name }}</p>    
</div>
<br>
<h3>Controller Two</h3>
<div ng-controller="ControllerTwo">
    <p>Via Assignment: {{age}}</p>
    <p>Via Assignment: {{user.name}}</p>
</div>

JavaScript

var myModule = angular.module('myModule', []);
myModule.factory('contactService', function($rootScope) {
    var model = {
        age  : '30 yrs',
        user : { 
            name : 'Lukas Ruebbelke' 
        },
        updateAge : function(age) {
            model.age = age;
        },
        updateName : function(name) {
            model.user.name = name;
        }                
    };
    
    return model;
});

function ControllerZero($scope, contactService) {
    $scope.text = contactService.age,
    $scope.onAgeChange = function(age) {
                             contactService.updateAge(age);
                           };

    $scope.onUserNameChange = function(name) {
                             contactService.updateName(name);
                           };
}

function ControllerOne($scope, contactService) {
    $scope.ageFn = function() {
        return contactService.age;    
    }
        
    $scope.user = contactService.user;            
}

function ControllerTwo($scope, contactService) {
    $scope.age = contactService.age;
    $scope.user = contactService.user;        
}

ControllerZero.$inject = ['$scope', 'contactService'];        
        
ControllerOne.$inject = ['$scope', 'contactService'];

ControllerTwo.$inject = ['$scope', 'contactService'];