AngularJS - 在指令中使用服务和控制器

时间:2015-11-07 05:14:56

标签: angularjs angularjs-directive angularjs-service angularjs-controller

我正在尝试在指令中使用服务和控制器。我有一个按钮指令,点击按钮,我想调用一个控制器方法()并调用该方法()内的服务。

AppService.$inject = [];
function AppService() {
    var name = "Name 1";

    function getName() {
      return name;
    }

    function setName(na) {
      name = na;
    }
    return {
      getName : getName,
      setName : setName
    };
}


    AppDirective.$inject = ['appService'];
    function AppDirective(appService) {
    //    var link = function(scope){
    //      scope.showMessage = function(){
    //        alert('you clicked the directive!');
    //      };
    //  };

        var DirectiveController = function($scope) {
            $scope.showMessage = function() {
                /*
        *****        I cannot access the appService here.  ******
                */
                alert('you clicked the directive!');
            };
        };

        return{   
        //link: link,
        template: "<button ng-click='showMessage()'>Button 2</button>",
        controller: DirectiveController    
      };
    }

这是完整的插件 http://plnkr.co/edit/w4UNtZ8CgEsVD0Nt5gqa

但不知何故,我无法访问指令控制器内的服务。请帮忙!!!

1 个答案:

答案 0 :(得分:3)

您需要随时在控制器函数中注入依赖项。

<强>代码

var DirectiveController = function($scope,appService) {

<强> PLUNKR