AngularJS服务在指令链接函数中未定义

时间:2017-08-28 13:28:20

标签: javascript angularjs angularjs-directive

我正在关注John Papa's Angular 1 conventions并且我正在尝试实现一个自定义指令,该指令需要在链接函数中使用名为$parse的角度服务,但该服务似乎不可用。

当调用uiSalesTotalDashboard函数时,服务可用,但是当调用链接函数时,服务似乎未定义?

(function() {
   'use strict';
   module.exports = uiDirectives.directive('uiSalesTotalDashboard', uiSalesTotalDashboard);
   uiSalesTotalDashboard.$inject = ['$parse'];

   function uiSalesTotalDashboard($parse) {
       // $parse is available
       var directive = {
           scope: {
               salesPeriods: '@',
               translations: '@'
           },
           link: link,
           restrict: 'E',
           templateUrl: '/Scripts/app/shared/ui/templates/sales-total-dashboard.html'
       };
       return directive;

       function link(scope, element, attrs) {
           // $parse is undefined
       }
   }
})();

我做错了什么?感谢。

1 个答案:

答案 0 :(得分:0)

我不确定你的代码,目前还不清楚,因为你没有展示你的角度模块定义或者我觉得有些不对劲。 以下代码有效。试着找出有什么区别。不要担心控制器部分,我添加它只是为了确保我的示例代码工作:)。感谢



angular.module('sample', [])
  .controller('sampleController', ['$scope',function($scope){
    $scope.title= 'I am sample controller';
  }])
  .directive('uiSalesTotalDashboard', uiSalesTotalDashboard);
  
  uiSalesTotalDashboard.$inject = ['$parse'];
  function uiSalesTotalDashboard($parse) {
       var directive = {
           scope: {
               salesPeriods: '@',
               translations: '@'
           },
           link: link,
           restrict: 'E',
           template: '<p>I am directive</p'
       };
       return directive;

       function link(scope, element, attrs) {
           // $parse is working in this code
            console.log('----Printing $parse : ---');
           console.log($parse);
       }
   }
&#13;
<!doctype html>
<html ng-app="sample">
  <head>
    <title>My AngularJS App</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
  </head>
  <body ng-controller="sampleController">
    <h1>{{title}}</h1>
    <ui-sales-total-dashboard></ui-sales-total-dashboard>
  </body>
</html>
&#13;
&#13;
&#13;