Angularjs 无法访问中指令中的服务
我在角度上是个新手,而且陷入了一个概念性的问题。我无法访问“helloWorld”指令中的“游戏”服务 预期=名称:魔兽争霸 实际=名称: 这是我的js和html文件: JS代码:Angularjs 无法访问中指令中的服务,angularjs,angular-directive,angular-services,Angularjs,Angular Directive,Angular Services,我在角度上是个新手,而且陷入了一个概念性的问题。我无法访问“helloWorld”指令中的“游戏”服务 预期=名称:魔兽争霸 实际=名称: 这是我的js和html文件: JS代码: var app = angular.module("app",[]); app.provider("game", function () { var type; return { setType: function (value) { type = value
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>
服务
{{title}}
类似这样的内容:
app.directive('helloWorld', ["game",function (game) {
return {
restrict: 'E',
scope: {},
link: function (scope, elem, attrs, ctrl) {
scope.title = game.title;
},
template: 'Name : {{title}}'
};
}])
在
控制器
中访问游戏服务,该服务将在模板
中提供。如果您只需要在模板
中使用它,请只在控制器
中插入它。。。您的链接
或其他功能不需要知道
app.directive('helloWorld', function () {
return {
controller: function($scope, game) {
$scope.game = game;
},
template: 'Name : {{game.title}}'
};
}])
这里有一个解决方案供大家玩玩 只需将视图使用的define变量设置为所需的值
app.directive('helloWorld', ["game", function(game) {
return {
template: 'Name : {{game.title}}',
link: function(scope) {
scope.game = game;
}
};
}])
游戏在您的范围内不可用。如果您使用指令,您应该使用带有链接函数的返回对象,您可以在那里为服务设置范围的属性。比如:link:{…,function(scope,elem,attrs,ctrl){scope.game=game;}我已经在指令中注入了game。它不会像它那样工作吗?是的,你注入了它,就像注入控制器一样,但是如果你查看你的appCtrl,你还需要做:$scope.title=game.title;我们不能直接使用game.title?模板:{game.title}“?作用域中仍然没有游戏,应该隔离该作用域以避免污染控制器作用域对不起,它应该是标题,因为该作用域没有游戏。标题…我已经编辑了它。是的,您也可以隔离该作用域。”