2

我在解析指令控制器中的服务时遇到问题。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="[email protected]*" 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> 

回答

2

你没有返回你的函数。

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} 
    }); 
+0

哦哇,哈哈。谢谢。这是我做的第一家工厂,因此原谅了我的错误。我必须再等8分钟才能授予您胜利。 – Skinner927

+0

我认识到这个错误,因为我已经做了很多次:) – mccainz

相关问题