<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js@1.4.3" data-semver="1.4.3" src="https://code.angularjs.org/1.4.3/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
<title>Updating scopes</title>
</head>
<body ng-app="App">
<h1>Scopes to Service</h1>
<div class="parent" ng-controller="Parent">
<h2>Parent controller</h2>
<ul>
<li ng-repeat="item in items">{{ item }}</li>
</ul>
<div class="child" ng-controller="Child">
<h2>Child controller</h2>
<ul>
<li ng-repeat="item in items">{{ item }}</li>
</ul>
</div>
<input ng-model="newItem" />
<button ng-click="addItem(newItem); newItem = undefined;">Add new item</button>
</div>
</body>
</html>
function fill(destination, source) {
for (var k = 0; k < source.length; k += 1) {
destination[k] = source[k];
}
destination.length = source.length
}
angular.module('App', [])
.service('Items', function ($interval) {
var items = ['foo', 'bar'];
var setItems = fill.bind(null, items);
$interval(function () {
var newItems = items.concat('item ' + (items.length + 1));
setItems(newItems);
}, 3000);
return {
all: items
};
})
.controller('Parent', function (Items, $scope) {
$scope.items = Items.all;
$scope.addItem = function (x) {
$scope.items.push(x);
};
})
.controller('Child', function ($scope) {
});
.parent {
border: red 1px solid;
border-radius: 5px;
padding: 10px;
}
.child {
border: blue 1px solid;
border-radius: 5px;
padding: 10px;
margin-bottom: 10px;
}
Steps
* initial parent controller with list
* list from the parent shown in the child controller
* move items to separate service
* broke connection between items in the scope and the service
* breaking connection after timeout by overwriting reference
* preserving the returned reference