2016-09-01 12 views
0

"directive"モジュール内の "service"モジュール内にある変数を監視する方法。 サービスモジュールがあります。変更時に変数を監視する方法Angularjs

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 }); 
}; 

は、私は、指令モジュール

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

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

私は、変数「メッセージ」を変更したときに指令モジュールが変更とtemplateUrlの新しい値を送信することを望んを持っています。 何かが得られたら、私はページに表示する必要があるので、常に変数を監視する必要があります

答えて

1

サービスを指示文に挿入する必要があります。

あなたのリンク機能で次に
angular.module('SGA').directive('message', 'messageService', function (messageService) { 

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

「messageService」のこの「メッセージ」はでabsatecidoされるサービスhttps://docs.angularjs.org/api/ng/service/ $ qを

+0

を使用して、スコープ変数を設定する時間を助けるために約束を調べます"インターセプター"。それはとにかく提供されるだろうか? –

+0

非厳密モードの角度を使用すると、サービスが利用可能であるとみなされ、それをつかむことを試みます。あなたがより厳しい注射をしたいなら、私はこのようなパターンに従うでしょうhttp://stackoverflow.com/questions/37396423/angular-configure-es6-syntax/37396615#37396615 – d3l33t

+0

私は理解していません –

関連する問題