注入服务

时间:2016-01-26 15:26:54

标签: javascript angularjs

angular.module(app_name).directive('name', ['service', function(service) {
  return {
    restrict: 'A',
    scope: {
      payload: '@trackClicksWithJson'
    },
    link: function(scope, element, attrs) {
      element.bind('click', function() {
        //what I had not accounted for in terms of getting service defined here
      });
    }
  };
}]);

调试常规方面的想法?服务似乎在其他代码区域中起作用,注意到它在单击回调中未定义

1 个答案:

答案 0 :(得分:0)

试试我编写的代码

它包括控制器,服务和指令。

你可以看到demo in jsfiddle

angular.module('app', [])
  .controller('ctrl', function() {
   
  })
  .service('service', [function() {
    var that = this;
    this.test = function(element) {
      alert("Test Service");     
      
    };
  }])
  .directive('test', ['service', function(service) {
    return {
      restrict: 'A',
      link: function(scope, element, attrs) {
        element.bind('click', function() {
          service.test();
        });
      }
    }
  }]);
#test{
  width:100px;
  height:30px;
  border:1px solid;
  background:white;
  cursor:pointer;
  line-height:30px;
  text-align:center;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="app">
  <div id="test" test ng-controller="ctrl as vm">
    Click Me
  </div>
</div>