2014-02-21 65 views
0

我的服務不工作。我不確定它是否正確。 我希望服務能夠在應用程序運行時添加項目,而其他功能則用於添加另一個功能textbox,但百萬個問題是結構是正確的嗎?這是正確的服務AngularJS

Services.factory('ItemsService', function() { 
    var Items = [{id: 1}, {id: 2}, {id: 3}]; 

return{ 

    addNewItem:function() { 
     var newItemNo = Items.length+1; 
     Items.push({'id':newItemNo}); 
    }, 

    showAddItem :function(Item) { 
     return Item.id === Items[Items.length-1].id; 
    } 

}; 
}); 

回答

1

這是我們寫的角度serivces

// make sure you know the differences between service and factory 
// you most likely going to want a service for this situation 
angular.module('moduleName').service('itemService', function(){ 

    var items = [{id: 1}, {id: 2}, {id: 3}]; 

    var addNewItem = function() { 
     var newItemNo= items.length + 1; 
     items.push({'id':newItemNo}); 
    }; 

    var showAddItem = function(Item) { 
     return Item.id === items[items.length-1].id; 
    }; 

    // revealing module pattern 
    return { 
     Items: items, 
     AddNewItem: addNewItem, 
     ShowAddItem: showAddItem 
    }; 

});