在指令中访问我的服务

时间:2014-03-02 07:20:30

标签: angularjs angularjs-directive angularjs-scope

我无法弄清楚如何从指令中访问我的测试服务。当我尝试提醒我的数据时,我得到该属性的“未定义”错误。

我的测试服务:

app.service('MyData', function () {
    return {
        name: "myName"
    }
});

我的指示

.directive('bountyslider', [
        '$log',
        function (MyData) {
            var directive = {
                restrict: 'AC',
                scope: {
                    maxBounty: '@',
                    minBounty: '@',
                    bountyAmount: '@',
                    bountyGreen: '='
                },
                link: function (scope, elm, attrs) {

                    var maxVal;
                    var minVal;
                    var bountyAmount;

                    alert(MyData.name);

                    attrs.$observe('bountyAmount', function (value) {
                        bountyAmount = value;
                    });

                    attrs.$observe('minBounty', function (value) {
                        minVal = value;
                    });

                    attrs.$observe('maxBounty', function(value) {
                        maxVal = value;

                        $slide.slider("option", "max", maxVal); // left handle should be at the left end, but it doesn't move
                        $slide.slider("option", "value", bountyAmount); // left handle should be at the left end, but it doesn't move
                        $slide.slider("value", $slide.slider("value")); //force the view refresh, re-setting the current value
                    });

                    var $slide = $('#slider').slider({
                        min: 0,
                        max: 30,
                        step: .5,
                        value: bountyAmount,
                        slide: function (event, ui) {
                            $('#bountyAmountInput').attr('value', ui.value).formatCurrency();


                            //BountyWarning.ShowBountyWarning(minVal, maxVal, ui.value);
                        }
                    });
                }
            };
            return directive;
        }
    ]);

3 个答案:

答案 0 :(得分:1)

请使用工厂,看它在this plunk中工作:

app.factory('MyData', function () {
    return {
        name: "myName"
    }
});

它也适用于服务,我想也许你拼错了一些东西。

答案 1 :(得分:1)

您需要将mydata注入您的服务

.directive('bountyslider', ["MyData", function(mydata){
  //custom logic
}]);

答案 2 :(得分:0)

使用.service注册的函数将作为构造函数调用以获取服务实例。在您的情况下,您可以尝试:

app.service('MyData', function () {
    this.name = "myName";
});