AngularJS:无法在指令控制器中解决服务



我在指示控制器内解决服务时遇到困难。

我是Angular的新手,所以如果我做错了,请原谅。

我在这里写了一个示例应用程序:plnkr.co/edit/qu97ddx8wa4ulvveqvy6?p=preview

我的问题基本上是在第15行上。我不知道如何将指令的控制器引用到我需要的服务。

如果您不想跳下站点,这是JS:

angular.module('reportApp', ['reportUtils'])
  .controller('reportCtrl', function() {
  })
  .directive('checkSummary', function() {
    return {
      restrict: 'E',
      scope: {
        ctype: '@type'
      },
      controller: ['$scope', 'complianceLookup',
        function($scope, complianceLookup) {
          // This is where I'm having trouble
          $scope.niceName = complianceLookup.shortToNice($scope.ctype);
          console.log($scope.niceName);
        }
      ],
      template: '<h1>who cares</h1>'
    }
  });
angular.module('reportUtils', [])
  .factory('complianceLookup', function() {
    var c = {
      NC: 'Not Compliant Checks',
      C: 'Compliant Checks',
      TBD: 'Checks Requiring Further Analysis',
      NA: 'Not Applicable',
      M: 'Manual Checks'
    };
    var shortToNice = function(short) {
      try {
        return c[short.toUpperCase()];
      } catch (e) {
        return '??';
      }
    }
  });

<!DOCTYPE html>
<html ng-app="reportApp">
  <head>
    <script data-require="angular.js@*" data-semver="1.2.13" src="http://code.angularjs.org/1.2.13/angular.js"></script>
    <link href="style.css" rel="stylesheet" />
    <script src="script.js"></script>
  </head>
  <body ng-controller="reportCtrl">
    <h1>Hello Plunker!</h1>
    <check-summary type="c"></check-summary>
  </body>

您没有返回您的功能。

angular.module('reportUtils', [])
  .factory('complianceLookup', function() {
    var c = {
      NC: 'Not Compliant Checks',
      C: 'Compliant Checks',
      TBD: 'Checks Requiring Further Analysis',
      NA: 'Not Applicable',
      M: 'Manual Checks'
    };
    var shortToNice = function(short) {
      try {
        return c[short.toUpperCase()];
      } catch (e) {
        return '??';
      }
    }
    return {shortToNice: shortToNice}
  });

最新更新