Angular: Model Factory Example

http://angularjs.org/

by sberube

HTML

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"></script>
<div ng-controller="MyCtrl">{{name}}&lrm;&nbsp;{{test}}
    <br>
    <br>{{test1.first}}
    <br>{{test2.first}}
    <br>{{test1.fullName()}}
    <br>{{test2.fullName()}}
    <button ng-click="test1.first = 'mike'">Click me</button>
</div>

JavaScript

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

//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

myApp.factory('TestModel', function () {
    function Test() {
        this.first = "";
        this.last = "";
        this.fullName = function () {
            return this.first + " " + this.last;
        }
    }

    return {
        mike: function () {
            window.alert('t');
        },
        new: function () {
            return new Test();
        }
    }
});

function MyCtrl($scope, TestModel) {
    $scope.name = 'Superhero';
    $scope.test = 'Test';

    $scope.test1 = TestModel.new();
    $scope.test1.first = "steve";
    $scope.test1.last = "berube";

    $scope.test2 = TestModel.new();
    $scope.test2.first = "steve2";
    $scope.test2.last = "berube2";
}