Javascript 将变量传递给 AngularJS 控制器,最佳实践?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11703477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:47:26  来源:igfitidea点击:

Pass variables to AngularJS controller, best practice?

javascriptjavascript-frameworkangularjs

提问by Greg

I am brand new to AngularJSand 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.

我是AngularJS 的新手,喜欢到目前为止我所看到的,尤其是模型/视图绑定。我想利用它来构建一个简单的“添加到购物篮”的功能。

This is my controller so far:

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

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

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

        ...

    };
}

And this is my HTML:

这是我的 HTML:

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

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.

现在这可行,但我非常怀疑这是在我的模型中创建新产品对象的正确方法。然而,这正是我完全缺乏 AngularJS 经验的地方。

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

如果这不是这样做的方法,那么最佳实践是什么?

采纳答案by Andrew Joslin

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

您可以创建一个篮子服务。通常在 JS 中,您使用对象而不是大量参数。

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

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

回答by Andrejs

You could use ng-initin an outer div:

您可以在外部 div 中使用ng-init

<div ng-init="param='value';">
    <div ng-controller="BasketController" >
        <label>param: {{value}}</label>
    </div>
</div>  

The parameter will then be available in your controller's scope:

然后该参数将在您的控制器范围内可用:

function BasketController($scope) {
        console.log($scope.param);
}

回答by Diego d'Ursel

I'm not very advanced in AngularJS, but my solution would be to use a simple JS class for you cart (in the sense of coffee script) that extend Array.

我在 AngularJS 方面不是很先进,但我的解决方案是为您的购物车使用一个简单的 JS 类(在咖啡脚本的意义上),它扩展了 Array。

The beauty of AngularJS is that you can pass you "model" object with ng-click like shown below.

AngularJS 的美妙之处在于你可以通过 ng-click 传递你的“模型”对象,如下所示。

I don't understand the advantage of using a factory, as I find it less pretty that a CoffeeScript class.

我不明白使用工厂的好处,因为我发现它不如 CoffeeScript 类漂亮。

My solution could be transformed in a Service, for reusable purpose. But otherwise I don't see any advantage of using tools like factory or service.

我的解决方案可以在服务中进行转换,以实现可重用的目的。但除此之外,我认为使用工厂或服务等工具没有任何优势。

class Basket extends Array
  constructor: ->

  add: (item) ->
    @push(item)

  remove: (item) ->
    index = @indexOf(item)
    @.splice(index, 1)

  contains: (item) ->
    @indexOf(item) isnt -1

  indexOf: (item) ->
    indexOf = -1
    @.forEach (stored_item, index) ->
      if (item.id is stored_item.id)
        indexOf = index
    return indexOf

Then you initialize this in your controller and create a function for that action:

然后在控制器中初始化它并为该操作创建一个函数:

 $scope.basket = new Basket()
 $scope.addItemToBasket = (item) ->
   $scope.basket.add(item)

Finally you set up a ng-click to an anchor, here you pass your object (retreived from the database as JSON object) to the function:

最后,您设置了一个锚点的 ng-click,在这里您将您的对象(从数据库中作为 JSON 对象检索)传递给函数:

li ng-repeat="item in items"
  a href="#" ng-click="addItemToBasket(item)"