[arrays] How to push objects in AngularJS between ngRepeat arrays

So I'm new to AngularJS and I'm trying to build a very simple list app, where I can create an ng-repeat item list and then push a selected item into another ng-repeat list. Although my problem seems to be very simple I wasn't able to find a proper solution yet.

So here's the simplified markup:

<body ng-app="MyApp">
 <div id="MyApp" ng-controller="mainController">

    <div id="AddItem">
         <h3>Add Item</h3>

        <input value="1" type="number" placeholder="1" ng-model="itemAmount">
        <input value="" type="text" placeholder="Name of Item" ng-model="itemName">
        <br/>
        <button ng-click="addItem()">Add to list</button>
    </div>
    <!-- begin: LIST OF CHECKED ITEMS -->
    <div id="CheckedList">
         <h3>Checked Items: {{getTotalCheckedItems()}}</h3>

         <h4>Checked:</h4>

        <table>
            <tr ng-repeat="item in checked" class="item-checked">
                <td><b>amount:</b> {{item.amount}} -</td>
                <td><b>name:</b> {{item.name}} -</td>
                <td> 
                   <i>this item is checked!</i>

                </td>
            </tr>
        </table>
    </div>
    <!-- end: LIST OF CHECKED ITEMS -->
    <!-- begin: LIST OF UNCHECKED ITEMS -->
    <div id="UncheckedList">
         <h3>Unchecked Items: {{getTotalItems()}}</h3>

         <h4>Unchecked:</h4>

        <table>
            <tr ng-repeat="item in items" class="item-unchecked">
                <td><b>amount:</b> {{item.amount}} -</td>
                <td><b>name:</b> {{item.name}} -</td>
                <td>
                    <button ng-click="toggleChecked($index)">check item</button>
                </td>
            </tr>
        </table>
    </div>
    <!-- end: LIST OF ITEMS -->
  </div>
</body>

And here goes my AngularJS Script:

var app = angular.module("MyApp", []);

app.controller("mainController",

function ($scope) {

// Item List Arrays
$scope.items = [];
$scope.checked = [];

// Add a Item to the list
$scope.addItem = function () {

    $scope.items.push({
        amount: $scope.itemAmount,
        name: $scope.itemName
    });

    // Clear input fields after push
    $scope.itemAmount = "";
    $scope.itemName = "";

};

// Add Item to Checked List and delete from Unchecked List
$scope.toggleChecked = function (item, index) {
    $scope.checked.push(item);
    $scope.items.splice(index, 1);
};

// Get Total Items
$scope.getTotalItems = function () {
    return $scope.items.length;
};

// Get Total Checked Items
$scope.getTotalCheckedItems = function () {
    return $scope.checked.length;
};
});

So when I click the button, my toggleChecked() function triggers and it actually pushes something into my checked list. However, it seems to be just an empty object. The function can't get the actual item that I want to push.

What am I doing wrong here?

NOTE: Checking items via click on a button is intended. I don't want to use checkboxes in this case.

You can see the working model here: http://jsfiddle.net/7n8NR/1/

Cheers, Norman

This question is related to arrays angularjs controller ng-repeat

The answer is


You'd be much better off using the same array with both lists, and creating angular filters to achieve your goal.

http://docs.angularjs.org/guide/dev_guide.templates.filters.creating_filters

Rough, untested code follows:

appModule.filter('checked', function() {
    return function(input, checked) {
        if(!input)return input;
        var output = []
        for (i in input){
            var item = input[i];
            if(item.checked == checked)output.push(item);
        }
        return output
    }
});

and the view (i added an "uncheck" button too)

<div id="AddItem">
     <h3>Add Item</h3>

    <input value="1" type="number" placeholder="1" ng-model="itemAmount">
    <input value="" type="text" placeholder="Name of Item" ng-model="itemName">
    <br/>
    <button ng-click="addItem()">Add to list</button>
</div>
<!-- begin: LIST OF CHECKED ITEMS -->
<div id="CheckedList">
     <h3>Checked Items: {{getTotalCheckedItems()}}</h3>

     <h4>Checked:</h4>

    <table>
        <tr ng-repeat="item in items | checked:true" class="item-checked">
            <td><b>amount:</b> {{item.amount}} -</td>
            <td><b>name:</b> {{item.name}} -</td>
            <td> 
               <i>this item is checked!</i>
               <button ng-click="item.checked = false">uncheck item</button>

            </td>
        </tr>
    </table>
</div>
<!-- end: LIST OF CHECKED ITEMS -->
<!-- begin: LIST OF UNCHECKED ITEMS -->
<div id="UncheckedList">
     <h3>Unchecked Items: {{getTotalItems()}}</h3>

     <h4>Unchecked:</h4>

    <table>
        <tr ng-repeat="item in items | checked:false" class="item-unchecked">
            <td><b>amount:</b> {{item.amount}} -</td>
            <td><b>name:</b> {{item.name}} -</td>
            <td>
                <button ng-click="item.checked = true">check item</button>
            </td>
        </tr>
    </table>
</div>
<!-- end: LIST OF ITEMS -->

Then you dont need the toggle methods etc in your controller


Try this one also...

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
_x000D_
  <p>Click the button to join two arrays.</p>_x000D_
_x000D_
  <button onclick="myFunction()">Try it</button>_x000D_
_x000D_
  <p id="demo"></p>_x000D_
  <p id="demo1"></p>_x000D_
  <script>_x000D_
    function myFunction() {_x000D_
      var hege = [{_x000D_
        1: "Cecilie",_x000D_
        2: "Lone"_x000D_
      }];_x000D_
      var stale = [{_x000D_
        1: "Emil",_x000D_
        2: "Tobias"_x000D_
      }];_x000D_
      var hege = hege.concat(stale);_x000D_
      document.getElementById("demo1").innerHTML = hege;_x000D_
      document.getElementById("demo").innerHTML = stale;_x000D_
    }_x000D_
  </script>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_


Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to angularjs

AngularJs directive not updating another directive's scope ERROR in Cannot find module 'node-sass' CORS: credentials mode is 'include' CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400 Print Html template in Angular 2 (ng-print in Angular 2) $http.get(...).success is not a function Angular 1.6.0: "Possibly unhandled rejection" error Find object by its property in array of objects with AngularJS way Error: Cannot invoke an expression whose type lacks a call signature

Examples related to controller

Empty brackets '[]' appearing when using .where How to return a html page from a restful controller in spring boot? How to call a function from another controller in angularjs? Angularjs - Pass argument to directive Why is it that "No HTTP resource was found that matches the request URI" here? Multiple controllers with AngularJS in single page app Can we pass model as a parameter in RedirectToAction? How to create separate AngularJS controller files? passing JSON data to a Spring MVC controller Get controller and action name from within controller?

Examples related to ng-repeat

Angular ng-repeat add bootstrap row every 3 or 4 cols How to push objects in AngularJS between ngRepeat arrays Adding parameter to ng-click function inside ng-repeat doesn't seem to work AngularJS : Custom filters and ng-repeat Angular ng-repeat Error "Duplicates in a repeater are not allowed." How to filter (key, value) with ng-repeat in AngularJs? ng-repeat :filter by single field Custom sort function in ng-repeat