Yehudi Mikhael
Yehudi Mikhael

Reputation: 69

How to monitoring a variable when change Angularjs

How to monitoring a varible which is in a "service" module inside of a "directive" module. I have a Service module.

angular
.module('SGA')
.service('messageService', [messageService]);
function messageService() {
var ctrl = this;    
this.messages = [];
this.send = function (message, type) {
    ctrl.messages.push({ text: message, type: type });
};

And i have a Directive module

angular.module('SGA').directive('message', function () {

return {
    restrict: 'E',
    scope: {},
    bindToController: {
        msg: '@'
    },
    templateUrl: "assets/templates/message/message.html",
    controllerAs: 'ctrl',
    link: function (){}
} 
})

I want that when the variable "messages " to change the directive module is changed and sent the new value for templateUrl. I need to be always monitoring the variable because when she gets something , I need to show on the page

Upvotes: 0

Views: 69

Answers (1)

d3l33t
d3l33t

Reputation: 890

You need to inject your service into the directive.

angular.module('SGA').directive('message', 'messageService', function (messageService) {

Then in your link function

link: function (scope){
    messageService.send("hello");
    scope.messages = messageService.getMessages();
}

Look into promises to help time setting up your scope variable using services https://docs.angularjs.org/api/ng/service/$q

Upvotes: 1

Related Questions