0

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

6 Comments

This "messages" of "messageService" will be absatecido by an "interceptor". It would be provided anyway ?
using non strict mode angular will assume the service is available and try to grab it. If you want to be more strict with injection i would follow a pattern like this stackoverflow.com/questions/37396423/…
I did not understand
sorry. can you rephrase your question?
I did not understand this part of an injection
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.