2016-10-27 4 views
0

追加項目で項目の名前を変更しますユーザー入力を使用する新しいlistItems配列Angularjsは、使用して新しい配列への1つの配列から配列

+0

なぜそれが可能ではないでしょうか? – tcooc

+0

** cityName **は、ng-repeatで反復処理しているデータのものですか? ** x.cityName **のようなもの? –

+0

ああ、これをx.idに変更するのはやめて、コードを簡略化して少し簡略化しました。 – Znowman

答えて

1

その可能性を確認してください。しかしあなたのコードが書かれている方法ではありません。あなたはidにではなく関数にオブジェクトを渡す必要があります。

<tr ng-repeat="x in data"> 
    <td>{{ x.id }}</td> 
    <td><input type="text" ng-model="newVal"/></td> <!--this property can be changed by user--> 
    <td><button type="button" ng-click="addToList(x, newVal)">Add to</button></td> 
</tr> 

とコントローラ機能で:

$scope.addToList = function(item, newVal) { 
    var newItem = item; 
    newItem.id = newVal; 
    $scope.listItems.push(item); 
    console.log($scope.listItems); 
    }; 
+0

私の最後に誤っていたのですが、実際の質問は、新しい入力項目配列の属性名をテキスト入力フィールドなどのユーザー入力によって変更できるかどうかです。 – Znowman

+0

プロパティ名またはプロパティ値?上記のidのような値 –

+0

の値を設定してください。 – Znowman

0

あなたは間違いなくそれを行うことができますが、そのためにはx.idではなくオブジェクト自体を渡す必要があります。

ここでは、動作するサンプルソリューションを示します。

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

 
app.controller("sampleController", ["$scope", 
 
    function($scope) { 
 
    $scope.data = [{ 
 
     id: "City-1" 
 
    }, { 
 
     id: "City-2" 
 
    }, { 
 
     id: "City-3" 
 
    }, { 
 
     id: "City-4" 
 
    }, { 
 
     id: "City-5" 
 
    }]; 
 

 
    $scope.listItems = []; 
 
    $scope.addToList = function(item) { 
 
     $scope.listItems.push(item); 
 
    }; 
 
    } 
 
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="sampleApp"> 
 
    <div ng-controller="sampleController"> 
 
    <table> 
 
     <tr ng-repeat="x in data"> 
 
     <td> 
 
      {{ x.id }}</td> 
 
     <td> 
 
      <button type="button" ng-click="addToList(x)">Add to</button> 
 
     </td> 
 
     </tr> 
 
    </table> 
 
    New List: 
 
    <table> 
 
     <tr ng-repeat="item in listItems track by $index"> 
 
     <td> 
 
      {{ item.id }}</td> 
 
     <td> 
 
      <button type="button" ng-click="addToList(x)">Add to</button> 
 
     </td> 
 
     </tr> 
 
    </table> 
 
    </div> 
 
</div>

関連する問題