/angularjs/

AngularJS – Directive Communication – Part 3

2014-08-05 22:37:30

Simple example of communication between directives via model object from common service.

GitHub &

app.js

angular.module('App', [])

    .service('simpleService', function () {

        var self = this;

        this.model = {todos: []};

        this.add = function (todo) {
            self.model.todos.push(todo);
        }

        this.get = function () {
            return self.model.todos;
        }

        this.delete = function (todo) {
            var index = self.model.todos.indexOf(todo);
            if (index > -1) {
                self.model.todos.splice(index, 1);
            }
        }
    })

    .directive('simpleForm', function (simpleService) {
        return {
            restrict: 'E',
            scope: {},
            templateUrl: 'simple-form.html',
            controller: function ($scope) {
                $scope.add = function () {
                    simpleService.add($scope.todo);
                    $scope.todo = {};
                }
            }
        }
    })

    .directive('simpleList', function (simpleService) {
        return {
            restrict: 'E',
            scope: {},
            templateUrl: 'simple-list.html',
            controller: function ($scope) {

                $scope.items = simpleService.get();

                $scope.delete = function (item) {
                    simpleService.delete(item);
                }
            }
        }
    })
;

index.html


<section ng-app='"App"'>
<simple-form></simple-form>
<simple-list></simple-list>
</section>

simple-list.html


<ul class='"list-group"'>
<li $index&quot;="" by="" class='"list-group-item"' in="" items="" ng-repeat='"item' track="">
        {{item}}
        <a href='""' ng-click='"delete(item)"'>x</a>
</li>
</ul>

simple-form.html


<div class='"form-inline"'>
<div class='"form-group"'>
<input ng-model='"todo.name"/' type='"text"'/>
</div>
<div class='"form-group"'>
<button ng-click='"add()"'>add</button>
</div>
</div>