2017-07-13 95 views
1

我正在將一個服務注入到一個指令中,對於某些情況下此服務返回undefined任何人都可以解釋我做錯了什麼?將服務注入指令返回undefined

以下是下面的代碼。 https://plnkr.co/edit/H2x2z8ZW083NndFhiBvF?p=preview

var app = angular.module('plunker', []); 

app.controller('MainCtrl', function($scope) { 
$scope.name = 'World'; 
$scope.players = ["A","B","C"]; 
}); 

app.factory('PlayerListS', [function() { 
    var playerList = []; 

    function getList() { 
     return playerList; 
    } 
    function addToList(name) { 
     playerList.push(name); 
    } 

    return { 
     addToList :addToList, 
     getList: getList 
    } 

}]); 
app.directive("player",['PlayerListS', function (PlayerListS) { 
return { 
    restrict: 'E', 
    scope: { 
     person:'@person', 
     add:'&add' 
    }, 
    replace: false, 
    templateUrl: "player.html", 
    controller: function($scope, $element, $compile) { 
      $scope.add = function(name) { 
       PlayerListS.addToList(name); 
       console.log(PlayListS.getList()); 
      } 
    } 
}; 
}]); 

回答

2

在控制檯中有一個輸入錯誤,因爲代碼會引發錯誤。改變你的指令通過以下方式

app.directive("player",['PlayerListS', function (PlayerListS) { 
    return { 
     restrict: 'E', 
     scope: { 
      person:'@person', 
      add:'&add' 
     }, 
     replace: false, 
     templateUrl: "player.html", 
     controller: function($scope, $element, $compile) { 
       $scope.add = function(name) { 
       debugger; 
        PlayerListS.addToList(name); 
        console.log(PlayerListS.getList()); 
       } 
     } 
    }; 
}]); 

工作演示https://plnkr.co/edit/HhmOYyoZAhm6vvXp3puC?p=preview

+1

是啊,你拼寫錯誤PlayerListS。你有PlayListS。 – terpinmd