StackOverflow_24130440: something-like-a-manual-refresh-is-needed-angularjs

Illustration of answer to http://stackoverflow.com/questions/24130440/something-like-a-manual-refresh-is-needed-angularjs.

by ExpertSystem

HTML

<script src="http://code.angularjs.org/1.2.16/angular.min.js"></script>
<div ng-controller="myCtrl as ctrl">
    <button ng-click="ctrl.reloadItems()">Reload items</button>
    <table>
        <tr ng-repeat="r in ctrl.lineItems">
            <td>{{r.text}}</td>
            <td>...</td>
            <td>{{r.price | currency}}</td>
        </tr>
    </table>
    <div ng-hide="ctrl.lineItems.length">Loading...</div>
</div>

JavaScript

var app = angular.module('myApp', []);
app.controller('myCtrl', function (OrderModel) {
    this.orderModel  = OrderModel;
    this.lineItems   = this.orderModel.lineItems;
    this.reloadItems = this.orderModel.getLineItems;

    this.reloadItems();
});

app.service('OrderModel', function ($timeout) {
    this.lineItems = [];
    this.getLineItems = function () {
        var total = 0;
        this.lineItems.splice(0, this.lineItems.length);
        $timeout(function () {
            for (var i = 0; i < 10; i++) {
                total++;
                this.lineItems.push({text: 'Order Total', price: total});
            }
        }.bind(this), 1000);
    };
});