无法访问 angular 指令中的服务

Not able to access service in directive in angular

我是 angular 的新手,遇到了一个概念性问题。我无法在 "helloWorld" 指令中访问 "game" 服务。

预期=名称:魔兽争霸

实际 = 姓名:

这是我的 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>

像这样:

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

controller 中访问您的游戏服务,这将在您的 template 中可用。如果您仅在 template 中需要它,则仅在 controller 中注入它...您的 link 或其他函数不需要知道。

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

这是 plunker 上的 解决方案 ,供大家试用。

只需定义视图将使用的变量并为其设置所需的值。

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