質問

My service don't work. I am not sure if it's right or not. I want The service to add items when the app runs , and their other function it's for add another textbox, but the million question is the structure is right?

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;
    }

};
});
役に立ちましたか?

解決

this is how we write angular 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
    };

});
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top