Dinesh Goyal
Dinesh Goyal

Reputation: 127

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>

Upvotes: 1

Views: 209

Answers (3)

Kunso Solutions
Kunso Solutions

Reputation: 7630

Here is solution on plunker, to play around.

Just put define variable which will be used by view and set to it needed value.

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

Upvotes: 0

Thomas Zo&#233;
Thomas Zo&#233;

Reputation: 423

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}}'
};
}])

Upvotes: 1

Thalaivar
Thalaivar

Reputation: 23632

Access your game service in controller, which will be available in your template. If you need it only in template, inject it only in controller... your link or other function need not know.

app.directive('helloWorld', function () {
    return {
        controller: function($scope, game) {
           $scope.game = game;
        },
        template: 'Name : {{game.title}}'
    };
}])

Upvotes: 0

Related Questions