Share data between directives in AngularJS 1x?

December 29, 2016

Today I need to share data between 2 directives in AngularJS 1x, using angular.copy the beerservice can be inject into each directive.

(function(){
    var app = angular.module('danyApp',\[\]);

    app.controller("homeController",function($scope,beerService ){

        $scope.title = "hello app";
       angular.copy(\[ { name: 'dany'} , { name: 'mgarocks' } \], beerService.elements);

    })

    app.directive('beer1', function(beerService){
        return {
            restrict: 'E',
            template: '<h3>Beer 1</h3>' + 
                '<div ng-repeat="item in data.elements">' + 
                '<input type="text" ng-model="item.name"/>' + 
                '</div>',
            link: function(scope, elem, attr) {
                scope.data = beerService;
            }
        };
    });

      app.directive('beer2', function(beerService){
        return {
            restrict: 'E',
            template: '<h3>Beer 2</h3>' + 
                '<div ng-repeat="item in data.elements">' + 
                '<input type="text" ng-model="item.name"/>' + 
                '</div>',
        link: function(scope, elem, attr) {
                scope.data = beerService;
            }
        };
    });

    app.factory('beerService', \[function(){
        return { elements: \[\] };
    }\]);

})();

The HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div class="container" ng-app="danyApp" ng-controller="homeController">
<h1 ng-bind="title"></h1>
<beer1></beer1>
<beer2></beer2>
</div>
<script src="bower\_components/angular/angular.js"></script>
<script src="app.js"></script>
</body>
</html>