Pass variables to AngularJS controller, best practice?

前端 未结 3 1498
难免孤独
难免孤独 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:54

    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.

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

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

    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:

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

提交回复
热议问题