Matan D
Matan D

Reputation: 141

AngularJS: Binding a service value to a directive

I am kind of new to AngularJS, and I tried to make my own directive.

My goal is to create a "clock" directive, which gets his data from a general service. The problem is that I didn't success to bind the value of the current time, from the service, to the directive (and to the view actually). The first value ("Loading") remains on the screen, instead of updating to the new value (the time). This is my code:

Javascript:

var mainApp = angular.module("mainApp", []);

// The service
mainApp.service('clockService', function($interval) {
    this.currentTime = "Loading...";

    function updateTime() {
        this.currentTime = Date.now();
    }

    $interval(updateTime, 1000);
});

// The directive
mainApp.directive('clock', function (clockService) {
    return {
        restrict: 'E',
        link: function (scope) {
            scope.model = clockService.currentTime;
        }
    };
});

mainApp.controller('testController', function($scope) {
});

HTML:

<body>
   <h2>AngularJS Sample Application</h2>

   <div ng-app="mainApp" ng-controller="testController">
        <clock>{{ model }}</clock>
   </div>

   <script src="angular-1.2.29/angular.min.js"></script>
   <script src="app.js"></script>

</body>

BTW, I guess this is not the best way to implement this idea, so if there is a better suggestion which also fixes my issue, I will be more than happy to hear about it either.

Thanks!

Upvotes: 2

Views: 881

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136184

Instead of creating primitive object there inside service, do create an object and then place currentTime property in it. And then you could refer that object inside a directive. As you bind reference of service variable to the directive scope. Changes in the service will change the value of directive variable.

Also you need to use date filter to format the data do show it in time format.

Markup

<div ng-app="mainApp" ng-controller="testController">
    <clock>{{ model.currentTime | date: 'hh: mm: ss' }}</clock>
</div>

Service

mainApp.service('clockService', function($interval) {
    this.model = {
        currentTime : "Loading..."
    };

    function updateTime() {
        this.model.currentTime = Date.now();
    }

    $interval(updateTime, 1000);
});

Directive

mainApp.directive('clock', function (clockService) {
    return {
        restrict: 'E',
        link: function (scope) {
            scope.model = clockService.model;
        }
    };
});

Demo Plunkr

Upvotes: 1

Related Questions