/java-script/

AngularJS – Directive Communication - Part 2

2014-08-01 19:28:23

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

1. app.js

angular.module('App', [])

    .controller('ModelCtrl', function ($scope) {
        $scope.model = {};
    })

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

                $scope.model.items = [];

                $scope.add = function () {
                    $scope.model.items.push($scope.item);
                    $scope.item = '';
                }
            }
        }
    })

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

2. part of index.html


<section ng-app='"App"' ng-controller='"ModelCtrl"'>
<section =="" ng-init='"model.subsectionaA' {}&quot;="">
<simple-form model='"model.subsectionaA"'></simple-form>
<simple-list model='"model.subsectionaA"'></simple-list>
</section>
<section =="" ng-init='"model.subsectionaB' {}&quot;="">
<simple-form model='"model.subsectionaB"'></simple-form>
<simple-list model='"model.subsectionaB"'></simple-list>
</section>
<h1>Current model:</h1>
<pre>{{model | json}}</pre>
</section>

3. simple-list.html

<ul><li $index&quot;="" by="" in="" model.items="" ng-repeat='"item' track="">{{item}}</li></ul>

4. simple-form.html


<input ng-model='"item"/' type='"text"'/>

<button ng-click='"add()"'>add</button>