<!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>
<parent class="parent">
</parent>
</body>
</html>
angular.module('App', [])
.service('Items', function ($interval) {
var items = ['foo', 'bar'];
$interval(function () {
// overwrite the reference
items = items.concat('item ' + (items.length + 1));
console.log('items', items);
}, 3000);
return {
all: items
};
})
.directive('parent', function () {
return {
restrict: 'E',
scope: {},
template: '<h2>Parent directive</h2>' +
'<ul>' +
'<li ng-repeat="item in items">{{ item }}</li>' +
'</ul>' +
'<child class="child" list="items"></child>',
controller: function ($scope, Items) {
$scope.items = Items.all;
}
};
})
.directive('child', function () {
return {
restrict: 'E',
scope: {
list: '='
},
template: '<h2>Child directive</h2>' +
'<ul>' +
'<li ng-repeat="item in list">{{ item }}</li>' +
'</ul>'
};
});
.parent {
border: red 1px solid;
border-radius: 5px;
padding: 10px;
display: block;
}
.child {
border: blue 1px solid;
border-radius: 5px;
padding: 10px;
margin-bottom: 10px;
display: block;
}
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
* controllers to directives
* split the link between scopes using isolate scopes
* show that digest cycle keeps scope synched even with separate references