问题是我有一个 ng-repeat,其源是一个 json 对象。
我有一个“添加项目”按钮,该按钮应该向该 json 对象添加一个新项目,同时呈现为 json 对象的一项以上。
但是这个项目,因为它是一个新项目,最初并不在 json 对象中,所以有机会在将其保存为该 json 对象的元素之前将其删除。
我不太确定这是否只是一个 Controller 操作,或者我应该在指令编译/链接函数中执行某些操作以呈现元素或执行其他操作。
以下代码只是我的想法的引用:
<div ng-controller="MyCtrl">
<button ng-click="example.addItem()"></button>
<div ng-repeat="item in example.jsonobject">
<p class="check-question">Question: {{item.question}}</p>
<p class="check-explanatory">Explanatory: {{item.explanatory}}</p>
<p ng-show="item.newItem === false" class="check-answer">Answer: {{item.answer}}</p>
<input ng-show="item.newItem === true" class="check-answer" ng-model="item.answer">Answer: {{item.answer}}</input>
<button ng-show="item.newItem === true" ng-click="example.removeItem()"></button>
</div>
</div>
最佳答案
解决您的问题的一种方法是为现有(且不可删除)项目和新项目使用单独的数组。
$scope.items = jsonobject;
$scope.newItems = [];
$scope.addItem = function(){
$scope.newItems.push($scope.newItem);
}
然后,添加到新数组中,该数组允许删除。当您最终“保存”时,它会转到主数组或提交给服务(或您所说的 jsonobject)。在 View 中,您可以使用 ng-repeat
对每个进行迭代。
我不太喜欢这种方法,因为它会让您为几乎相同的 HTML 结构编写两次 ng-repeat
。
另一种方法是用额外的元数据来装饰您的对象以表示新项目。我会避免更改实际模型,而是使用额外的元数据创建模型的 ViewModel 表示。
$scope.items = [];
angular.forEach(myService.getData(),
function(item){
$scope.items.push({isNew: false, item: item});
});
$scope.addItem = function(){
$scope.items.push(
{ isNew: true,
item: $scope.newItem // $scope.newItem is set by the input fields
});
}
在这种情况下,您只需执行一次 ng-repeat
<div ng-repeat="item in items">
<div>Question: {{item.item.q}}</div>
<div>Answer: {{item.item.a}}</div>
<button ng-if="item.isNew">Remove</button>
</div>
编辑:
这是一个plunker两种方法都可以。
关于javascript - 在 ng-repeat View 和 json 对象中添加元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26614437/