簡體   English   中英

使用服務內部指令?

[英]Using service inside directive?

我正在學習如何創建自定義指令。

我的服務如下所示:

myApp.service('myService',function(){
    this.myFunction=function(myParam){
        // do something
    }
});

這是我的指令

myApp.directive('myDirective',function(myService){
    return {
        restrict: 'E',
        scope: {
          param: '=myParam',
        },
        template: '<button ng-click="myService.myFunction(param)">Do action</button>',
    }
});

在HTML中,當我使用<my-directive my-param="something"></my-directive>它可以正確地呈現為按鈕。 但是,當我單擊它時, myService.myFunction不會執行。

我想我做錯了。 有人可以給我指示嗎? 我想這與指令的范圍有關。

該服務將無法直接在模板內部使用。 您必須使用附加到指令scope的函數,然后從該函數中調用service函數。

myApp.directive('myDirective',function(myService){
    return {
        restrict: 'E',
        scope: {
          param: '=myParam',
        },
        template: '<button ng-click="callService(param)">Do action</button>',
        link: function(scope, element, attrs) {
            scope.callService = function() {
                myService.myFunction();
            }
        }
    }
});

它不起作用,因為在您的示例中,指令實際上並不知道myService是什么。 您必須明確注入它,例如:

myApp.directive('myDirective', ['myService', function(myService){ ... }]);

另請參閱此問題或此問題

您應該使用控制器來進行所有DOM修改。
看到這個plunkr: https ://plnkr.co/edit/HbfD1EzS0av5BG6NgtIv ? p = preview

.directive('myFirstDirective', [function() {
  return {
    'restrict': 'E',
    'controller': 'MyFirstController',
    'controllerAs': 'myFirstCtrl',
    'template': '<h1>First directive</h1><input type="text" ng-model="myFirstCtrl.value">'
  };
}

您可以將服務注入控制器,然后在模板中調用該函數:

myService注入控制器:

myApp.controller("ctrl", function($scope, myService) {
    $scope.doService = function(myParam) {
        return myService.myFunction(myParam);
    };
});

在模板內調用控制器的doService方法:

myApp.directive('myDirective',function(){
    return {
        restrict: 'E',
        scope: {
          param: '=myParam',
        },
        template: '<button ng-click="doService(param)">Do action</button>',
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM