0

I'm new in AngularJS, I want to create an array and post it to server by register function, here's Controller code:

root.controller('mainController', function($scope) {
    $scope.lineItems = [];
    $scope.addItem = function (id) {
        $scope.lineItems.push(id);
        console.log($scope.lineItems);
        // gives me right data -> Array [ "1", "2", "3", "4", "1" ]
    };
    $scope.register = function () {
        // post data to server
        console.log($scope.lineItems);
        // gives me an empty array -> Array [ ]
    };
});

Here's HTML code and directives:

<div class="container" ng-controller="mainController">
    <a ng-click="register()"></a>

    <div ng-repeat="product in products">
        <a class="btn" ng-click="addItem(product.id)">Add</a>
    </div>
</div>

The problem occurs when i want to call register function, it gives me an empty array instead of array elements while it's not gonna happen in addItem function.

12
  • when you click on the anchor tag, does it console.log properly? Commented Apr 30, 2016 at 10:00
  • What do you mean by anchor tag? Commented Apr 30, 2016 at 10:01
  • <a> is an anchor tag Commented Apr 30, 2016 at 10:02
  • Yes! addItem function logs correctly. Commented Apr 30, 2016 at 10:03
  • 1
    Could you share a copy of the code in a Plunker? From what you've shown, everything should be working as expected. Commented Apr 30, 2016 at 10:11

1 Answer 1

1

This is your code and work correctly.

var app = angular.module("testApp", []);
app.controller('testCtrl', function($scope){
  
    $scope.products = [{id:1},{id:2},{id:3},{id:4}];
  
  $scope.lineItems = [];
    $scope.addItem = function (id) {
        $scope.lineItems.push(id);
        console.log($scope.lineItems);
        // gives me right data
    };
    $scope.register = function () {
        // post data to server
        console.log($scope.lineItems);
        // gives me an empty array
    };

  
 
});
<div ng-app="testApp" ng-controller="testCtrl">
   <a ng-click="register()">Register</a>

<div ng-repeat="product in products">
    <a class="btn" ng-click="addItem(product.id)">Add : {{product.id}}</a>
</div>
   
</div>

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, I think I made a simple mistake.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.