我在指令控制器中解析服务时遇到了问题。
我对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>
答案 0 :(得分: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}
});