Pass variables to AngularJS controller, best practice?

前端 未结 3 1495
难免孤独
难免孤独 2020-11-29 17:13

I am brand new to AngularJS and like what I\'ve seen so far, especially the model / view binding. I\'d like to make use of that to construct a simple \"add

3条回答
  •  暖寄归人
    2020-11-29 17:46

    You could create a basket service. And generally in JS you use objects instead of lots of parameters.

    Here's an example: http://jsfiddle.net/2MbZY/

    var app = angular.module('myApp', []);
    
    app.factory('basket', function() {
        var items = [];
        var myBasketService = {};
    
        myBasketService.addItem = function(item) {
            items.push(item);
        };
        myBasketService.removeItem = function(item) {
            var index = items.indexOf(item);
            items.splice(index, 1);
        };
        myBasketService.items = function() {
            return items;
        };
    
        return myBasketService;
    });
    
    function MyCtrl($scope, basket) {
        $scope.newItem = {};
        $scope.basket = basket;    
    }
    

提交回复
热议问题