JCIre JCIre - 1 month ago 18
AngularJS Question

Angular JS: Updating $Scope.Array through user input

I have created a simple angular application - which holds an array of strings.

On the front end - there is a single text input field - which when submitted, calls a function which should push this input to the $scope.array.

All values of the $scope.array are output on the same page, below the text input area.

I would like for the latest inputs to be displayed with the rest of the array value outputs on the front end - in essence, working an example of 2 way binding with angular.

However, when I submit the input value, the output is not updated on the front end - and I do not see why. Please find an example of the code below:

<!DOCTYPE html>
<html ng-app="App">
<head>
<title>First app - CRUD</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script src="js/app.js"></script>
<style></style>
</head>

<body>

<div class="header" align="center">
<h1>CRUD Application v1</h1>
</div>

<div ng-controller="ctrl1" class="main">

Name: <input type="text" ng-model="players.name">
<button ng-click="updateValue()">submit data</button>
<br><br>

<p>{{players.name}}</p>


<p ng-repeat="player in players" ng-model="players.name" class="main">
{{player.name}}
</p>


</div>

</body>


var app = angular.module('App', []);
app.controller('ctrl1', function ($scope){

//$scope.name = ' ';

//$scope.players = {"alonso", "gerrard"};

$scope.players = [{name:'alonso'}, {name:'gerrard'}];


$scope.updateValue = function(players){

// take input value and add to collection.
// send collection via ajax to server


$scope.players.push(players.name);
$scope.name = '';

};

});


Further to this - is it recommended to work directly with JSON objects or arrays when using angular?

Answer

Try to define a $scope variable for the input box and add push the value to the name property of the player object,

Controller

  $scope.players = [{
    name: 'alonso'
  }, {
    name: 'gerrard'
  }];
  $scope.newplayer = '';
  $scope.updateValue = function() {
    $scope.players.push({
      name: $scope.newplayer
    });
  };

});

HTML:

<body>
  <div class="header" align="center">
    <h1>CRUD Application v1</h1>
  </div>
  <div ng-controller="ctrl1" class="main">
    Name:
    <input type="text" ng-model="newplayer">
    <button ng-click="updateValue()">submit data</button>
    <br>
    <br>
    <p>{{players.name}}</p>
    <p ng-repeat="player in players"  class="main">
      {{player.name}}
    </p>
  </div>
</body>

DEMO