传递变量AngularJS控制器,最佳做法? [英] Pass variables to AngularJS controller, best practice?

查看:141
本文介绍了传递变量AngularJS控制器,最佳做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是全新的,以 AngularJS 并像什么我到目前为止看到的,尤其是模型/视图结合。我想利用,要构建一个简单的添加到购物篮的功能块。

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 to basket" piece of functionality.

这是我的控制器至今:

function BasketController($scope) {
    $scope.products = [];

    $scope.AddToBasket = function (Id, name, price, image) {

        ...

    };
}

这是我的HTML:

And this is my HTML:

<a ng-click="AddToBasket('237', 'Laptop', '499.95', '237.png')">Add to basket</a>

现在这个工作,但我很怀疑这是建立在我的模型一个新的产品对象的正确途径。然而,这就是我完全没有经验AngularJS进场。

Now this works but I highly doubt this is the right way to create a new product object in my model. However this is where my total lack of AngularJS experience comes into play.

如果这不是要做到这一点,什么是最好的做法是什么?

If this is not the way to do it, what is best practice?

推荐答案

您可以创建一个篮子服务。而且一般在JS使用对象而不是大量的参数。

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

下面是一个例子: 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;    
}

这篇关于传递变量AngularJS控制器,最佳做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆