通过Angular中的指令输出服务属性值

时间:2014-08-29 19:45:23

标签: angularjs

我的目标是通过元素指令输出一个值(来自服务),以便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>

对于代码或功能使用中的任何错误,我很抱歉,我对Angular来说还不错。

2 个答案:

答案 0 :(得分: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已经为这个常见用例做好了准备。解决方案涉及创建隔离范围。可以使用父环境中的属性填充隔离范围。一种可能性是使用&#34; @&#34;来使用指令元素中DOM属性的值。句法。在这种情况下,您甚至不需要整个MsgService服务:

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

答案 1 :(得分:0)

最简单的方法是在您的范围内设置服务并在模板中使用该服务:

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