如何在ng-repeat中更改单个div的内容

时间:2016-02-07 18:24:55

标签: javascript angularjs

我有这个角度代码。

<div ng-repeat="item in items | filter:search" class="container">
            <h3>{{item.name}}</h3>
            <p>category:{{item.category}}</p>
            <p>price:INR {{item.price}} /-</p>
            <br/>
            <button ng-hide="showme" ng-click="process(item.name,item.price)">Add</button>
            <button ng-show="showme" class="ng-cloak">Remove</button>
        </div>``

现在我想要的是每当我点击按钮应该隐藏的div中的添加按钮时,应该显示一个删除按钮。我能够做到这一点,但所有的div都在改变。我想改变单击该按钮的div。

这是我的控制器代码

var myApp = angular.module('myApp',[]);
myApp.controller('restaurantController', function($scope, $http){
    $http.get('apna.json').success(function (data){
        $scope.items = data;
    });
    $scope.showme=false;
    $scope.process = function(name,value){
        $scope.total = parseInt($scope.total) + parseInt(value);
        $scope.showme = true;
    }
});

2 个答案:

答案 0 :(得分:1)

您的showme变量位于$scope,因此每个项目都没有获得新的showme变量/属性来保存其个别设置。因此,您可以在$scope上设置一个新属性,而不是将其放在item上,而不是添加它。然后使用它在ng-show / hide中进行测试。

<button ng-hide="item.added" ng-click="process(item)">Add</button>
<button ng-show="item.added" class="ng-cloak">Remove</button>

并在您的process方法

item.added = true;

演示

var myApp = angular.module('myApp',[]);
myApp.controller('restaurantController', function($scope, $http){
    $scope.items = [
      {name:"Item 1",category:"food",price:19},
      {name:"Item 2",category:"auto",price:39},
      {name:"Item 3",category:"software",price:13}
    ];
    $scope.total = 0;
    $scope.process = function(item){
        $scope.total = parseInt($scope.total) + parseInt(item.price);
        item.added = true;
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="restaurantController">
  Total: {{total}}<br>
  <div ng-repeat="item in items | filter:search" class="container">
    <h3>{{item.name}}</h3>
    <p>category:{{item.category}}</p>
    <p>price:INR {{item.price}} /-</p>
    <br/>
    <button ng-hide="item.added" ng-click="process(item)">Add</button>
    <button ng-show="item.added" class="ng-cloak">Remove</button>
  </div>
</div>

答案 1 :(得分:1)

您可以为items数组指定 showme 字段,并为 false 赋值,并在ng-show和ng-hide指令中使用 item.showme 。同样在 process()中更改与该项目相关的 showme 变量