我是角度新人,陷入概念性問題。我無法在「helloWorld」指令中訪問「遊戲」服務。無法訪問指令中的角度服務
預期=名稱:魔獸爭霸
實際=名稱:
這是我的JS和HTML文件:
JS代碼:
var app = angular.module("app",[]);
app.provider("game", function() {
var type;
return {
setType: function (value) {
type = value;
},
$get: function() {
return {
title: type + "Craft"
};
}
};
});
app.config(function (gameProvider) {
gameProvider.setType("War");
});
app.controller("AppCtrl", function ($scope,game) {
$scope.title = game.title;
});
app.directive('helloWorld', ["game",function (game) {
return {
template: 'Name : {{game.title}}'
};
}])
HTML:
<title>Services</title>
<script src="angular.min.js"></script>
<script src="my-file.js"></script>
</head>
<body ng-app="app">
<div ng-controller="AppCtrl">{{title}} </div>
<hello-world></hello-world>
</body>
遊戲不適用於您的範圍。 如果你使用一個指令,你應該使用一個鏈接函數返回一個對象,你可以將你的作用域的屬性設置爲該服務。 like:link:{.....,function(scope,elem,attrs,ctrl){ scope.game = game;} –
我已經在指令中注入了遊戲。它不會像它一樣工作? –
是的,你注入它,就像你注入到控制器,但如果你看看你的appCtrl,你也需要做:$ scope.title = game.title; –