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

相關問題