Json文件的Angular js .push方法无法正常工作

时间:2017-07-07 07:22:42

标签: javascript angularjs json

当我尝试通过.push方法将随机数据输入到Array或Json文件时,它无法正常工作 这是我的代码 数组代码是

size_t

尝试通过ng-model绑定

 $scope.stock =[{
"name":"Pepsi",
"price":65,
"color":"black",
"avaliable":true}]

JS代码是

<form ng-submit="addItem()">
    <input type="text" placeholder="Name" ng-model="newName" />
    <input type="text" placeholder="Price" ng-model="newPrice" />
    <input type="text" placeholder="color" ng-model="newcolor" />
    <input class="submit" type="submit" value="Add New Item" />
</form> 

2 个答案:

答案 0 :(得分:0)

//try this
$scope.stock = [];

$scope.addItem = function(){
$scope.stock.push({
    name: $scope.newName,
    price: parseInt($scope.newPrice),
    color: $scope.newcolor,
    avaliable: true
});

答案 1 :(得分:0)

它的角度为1.4.6,请点击此处Jsfiddle demo

angular.module('myApp', ['ngStorage']).controller('ctrl',
  function($scope, $localStorage) {

    $scope.stock = [{
      "name": "Pepsi",
      "price": 65,
      "color": "black",
      "avaliable": true
    }]

    $scope.addItem = function() {
      $scope.stock.push({
        name: $scope.newName,
        price: parseInt($scope.newPrice),
        color: $scope.newcolor,
        avaliable: true
      });
    }
  });