2014-08-29 83 views
0

我的目標是通過元素指令輸出一個值(來自服務),使得html看起來像這樣<msg msg="alertMsg"></msg>,並從服務中彈出一個值。通過角度指令輸出服務屬性值

這裏是我的代碼至今:

app.directive("msg", ['MsgService', function(MsgService) { 
    return { 
     restrict: "E", 
     scope: {//something here to pass MsgService to template }, 
     template: 'Message:{{MsgService.getAlertMsg()}}' 
    }; 
}]); 

app.service('MsgService', function() {   
    this.alertMsg = 'default'; 
    this.getAlertMsg = function(){ 
     return this.alertMsg; 
    }; 
    this.setAlertMsg = function(string) { 
     this.alertMsg = string; 
    }; 
}); 

HTML將會解析/編譯成...

<msg msg="alertMsg">Message: default</msg> 

我需要什麼其他的代碼?

如果服務不能直接使用,我應該通過控制器訪問它嗎?

app.directive("msg", function() { 
    return { 
     restrict: "E", 
     scope: {  
      getMsg: '&msg' 
     }, 
     controller: 'MsgController', 
     template:'Message:{{getMsg()}}' 
    }; 
}]); 

app.controller('MsgController', ['MsgService' , function(MsgService){ 
    this.getAlertMsg = function(){ 
     return MsgService.getAlertMsg(); 
    }; 
}]); 

HTML將會解析/編譯成...

<msg msg="getAlertMsg()">Message: default</msg> 

對不起,代碼或功能使用任何錯誤,我是相當新的角度。

+0

如何在鏈接/你的指令控制器函數你說angular.extend(範圍,MsgService)? – 2014-08-29 19:51:06

+0

我甚至不知道這個功能是否存在......我不明白它的意思。 – JerryA 2014-08-29 19:53:41

+0

你的問題是什麼?上述指令代碼似乎工作正常。 – tommybananas 2014-08-29 20:25:19

回答

0

您可以使用指令的link函數。對於您的指令的每個呈現實例,此函數都會調用一次。除其他事項外,它還收到您的指示的範圍。你可以調用MsgSevice.getAlertMsg()服務方法的結果很容易地擴展您的範圍:

var app = angular.module("app", []); 
app.directive("msg", ['MsgService', function(MsgService) { 
    return { 
     restrict: "E", 
     scope: true, 
     template: 'Message:{{msg}}', 
     link: function (scope, $element, attrs) { 
      scope.msg = MsgService.getAlertMsg(); 
     } 
    }; 
}]); 

app.service('MsgService', function() { 
    this.alertMsg = 'default'; 
    this.getAlertMsg = function(){ 
     return this.alertMsg; 
    }; 
    this.setAlertMsg = function(string) { 
     this.alertMsg = string; 
    }; 
}); 

後來,我相信你會只想從msg指令的msg DOM屬性顯示警報消息。實現這一點非常簡單,因爲AngularJS已經爲這個常見用例做好了準備。解決方案涉及創建隔離範圍。可以使用父環境的屬性填充隔離範圍。一種可能性是使用「@」語法從指令元素中使用DOM屬性的值。在這種情況下,你甚至不需要整個MsgService服務:

app.directive("msg", function() { 
    return { 
     restrict: "E", 
     scope: { 
      "msg": "@" 
     }, 
     template: 'Message:{{msg}}' 
    }; 
}); 
+0

謝謝Razvan的非常詳細的答案。我會爲我工作。我正在使用我的所有控制器的MsgService。消息將通過指令顯示,範圍與指令設置的內容隔離。我將能夠通過html標籤上的屬性值選擇要顯示的消息。 – JerryA 2014-08-29 22:13:38

0

最簡單的是設置在你的範圍內的服務和使用,在您的模板:

app.directive("msg", ['MsgService', function(MsgService) { 
    return { 
     restrict: "E", 
     scope: { }, 
     template: 'Message:{{MsgService.getAlertMsg()}}', 
     link: function(scope, element, attrs) { 
      scope.MsgService = MsgService; 
     } 
    }; 
}]); 
+0

這與我正在尋找的東西非常接近,並且一定會做到,我應該能夠正確地做到我想要的那個attrs參數。謝謝! – JerryA 2014-08-29 22:09:25