Dinesh Goyal Dinesh Goyal - 3 months ago 16
AngularJS Question

Not able to access service in directive in angular

I am new in angular and stuck in a conceptual problem. I am not able to access "game" service in "helloWorld" directive.

expected = Name : WarCraft

Actual = Name :

Here is my js and html file :

JS code :

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>

Answer

something like this:

  app.directive('helloWorld', ["game",function (game) {
  return {
  restrict: 'E',
  scope: {},
  link: function (scope, elem, attrs, ctrl) {
    scope.title = game.title;
  },
  template: 'Name : {{title}}'
};
}])
Comments