質問

I'm having trouble resolving a service inside a directive controller.

I'm fairly new to Angular so please excuse me if I'm doing this completely wrong.

I've written a sample app here: plnkr.co/edit/Qu97ddX8wA4ULVveQVy6?p=preview

My problem is basically on line #15. I can't figure out how to pass the directive's controller reference to the service I need.

Here's the JS if you don't feel like hopping off site:

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>

役に立ちましたか?

解決

You weren't returning your function.

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}
  });
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top