Search code examples
javascriptangularjsangularjs-directiveangularjs-scope

Bind a service variable to a directive?


I have a controller which contains a function that gets some data from the server. I store that data in a service variable. This service is then injected into a directive. I want the directive to be auto updated, whenever this function is called and the data is renewed.

My controller:

angular
.module('myApp')
.controller('myCtrl', ['$scope', 'SomeService', function($scope, SomeService) {
    $scope.update = function() {
        SomeService.myValue = 100;
    }
}]);

The directive:

angular.module('myApp')
.directive('myDirective', ['SomeService', function(SomeService) {
    return {
        templateUrl : 'views/myDirective.html',
        restrict : 'E',
        scope : false,
        controller : function($scope) {
            this.myValue = SomeService.myValue;
        }
    };
}]);

The template:

<div>
    {{ myValue }}
</div>

The update function is called when a button is clicked and it updates myValue to a new value. I want it to be automatically reflected in the directive.

Plunk: http://plnkr.co/edit/OUPzT4MFS32OenRIO9q4?p=preview


Solution

  • Please see working demo below

    var app = angular.module('app', []);
    
    app.controller('MainCtrl', function($scope, SomeService) {
      $scope.name = SomeService.data;
    
      $scope.update = function() {
    
        $scope.name.myValue += 1;
      }
    
    });
    
    app.factory('SomeService', function() {
      var data = {
    
        myValue: 0
    
      };
    
      return {
    
        data: data
    
      }
    });
    
    
    app.directive('myDirective', ['SomeService',
      function(SomeService) {
        return {
          templateUrl: 'myDirective.html',
          restrict: 'EA',
          scope: false,
          link: function(scope, elem, attr) {
    
            scope.data = SomeService.data
    
          }
        };
      }
    ]);
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="app">
      <div ng-controller="MainCtrl">
        <p>My Value: {{name.myValue}}</p>
        <button ng-click="update()">Click</button>
        <hr/>
        <div my-directive></div>
    
        <script type="text/ng-template" id="myDirective.html">
          <h3>My Directive</h3>
          <p>Value: {{data.myValue}}</p>
        </script>
      </div>
    </div>