将变量传递给 AngularJS 控制器,最佳实践? [英] Pass variables to AngularJS controller, best practice?

查看:30
本文介绍了将变量传递给 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.

到目前为止,这是我的控制器:

This is my controller so far:

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

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

        ...

    };
}

这是我的 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天全站免登陆