2016-08-25 40 views
1

我是角度新人,陷入概念性問題。我無法在「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> 
+1

遊戲不適用於您的範圍。 如果你使用一個指令,你應該使用一個鏈接函數返回一個對象,你可以將你的作用域的屬性設置爲該服務。 like:link:{.....,function(scope,elem,attrs,ctrl){ scope.game = game;} –

+0

我已經在指令中注入了遊戲。它不會像它一樣工作? –

+0

是的,你注入它,就像你注入到控制器,但如果你看看你的appCtrl,你也需要做:$ scope.title = game.title; –

回答

1

是這樣的:在controller

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

template:'Name:{{game.title}}'? –

+0

範圍內還沒有遊戲 –

+0

而範圍應該是隔離的,以避免污染控制器範圍 –

0

訪問遊戲服務,這將在你的template可用。如果您只需要template,只需在controller ...中注入您的link或其他功能不需要知道。

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

這裏是plunker解決,身邊打球。

只是把定義的變量,將被視圖使用,並設置爲它需要的值。

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