angular
.module('demo', [])
.controller('PersonController', PersonController)
.directive('peopleList', PeopleListDirective)
.factory('peopleService', PeopleService);
function PeopleService() {
var peopleSubject = new Rx.ReplaySubject();
var service = {
subscribe: function(subscription) {
peopleSubject.subscribe(subscription);
},
add: function(people) {
people.push({
name: 'Name ' + (people.length + 1)
});
// broadcast
peopleSubject.onNext(people);
}
};
return service;
}
function PersonController(peopleService) {
var vm = this;
vm.people = [];
peopleService.subscribe(function(people) {
vm.people = people;
});
}
function PeopleListDirective() {
return {
controllerAs: 'peopleListCtrl',
controller: function($scope, $attrs, peopleService) {
this.people = $scope.$eval($attrs.people);
this.add = function() {
peopleService.add(this.people);
}.bind(this);
}
}
}
<!DOCTYPE html>
<html ng-app="demo">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.1/angular.js" data-semver="1.4.1"></script>
<script data-require="rxjs@*" data-semver="2.5.3" src="//cdnjs.cloudflare.com/ajax/libs/rxjs/2.5.3/rx.all.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="PersonController as personCtrl">
<!-- personCtrl -->
<people-list people="personCtrl.people">
<!-- personCtrl -->
<button ng-click="peopleListCtrl.add()">Add</button>
<div ng-repeat="person in peopleListCtrl.people">
Name: {{ person.name }}
</div>
</people-list>
</body>
</html>
/* Put your css in here */