2017-02-16 49 views
1

我有這個ngRepeat。我想創建某種切換,以便當用戶單擊按鈕時,輸入顯示,但是,我希望所有其他顯示的輸入隱藏(如果它們已經可見)。ng-repeat的角度顯示隱藏切換

<ul> 
    <li ng-repeat="(key, value) in jewel"> 
     <span ng-show="!showMe">text here</span> 
     <input ng-show="showMe"> 
     <button ng-click="showMe = true"></button> 
    </li> 
</ul> 

希望這是有道理的。

+0

你嘗試過NG-秀=和輸入NG- 「SHOWME!」 hide =「!showMe」 –

回答

0

ng-repeat具有隔離範圍,這就是爲什麼要影響你需要通過父變量的變量跟蹤其可見性的所有其他輸入。我prepeared一撥弄例如:http://jsfiddle.net/ancvgc1b/

angular 
    .module('myApp', ['ui.bootstrap']) 
    .controller('ExampleController', function($scope){ 
     $scope.jewel = { 
     key1: 'Foo', 
     key2: 'Bar' 
     }; 
     $scope.visible = { key: 'key1' }; 

     $scope.setVisible = function(key) { 
     $scope.visible.key = key; 
     } 
    }); 

<body ng-app="myApp"> 
    <div ng-controller='ExampleController'> 
    <ul> 
     <li ng-repeat="(key, value) in jewel"> 
     <span ng-show="!(visible.key == key)">Text value</span> 
     <input ng-show="visible.key == key"> 
     <button ng-click="setVisible(key)">show input</button> 
     </li> 
    </ul> 
</div> 
</body> 
+0

ng-repeat使子作用域,而不是隔離作用域。 解決方案是可以的,但可以減少冗長。 – pranavjindal999

0

快速修復:

<ul ng-init="active={}"> 
    <li ng-repeat="(key, value) in jewel"> 
     <span ng-show="!($index==active.index)">text here</span> 
     <input ng-show="$index==active.index"> 
     <button ng-click="active.index = $index"></button> 
    </li> 
</ul> 

如果使用controllerAs,它會導致更清潔的代碼如下: (VM是你的別名控制器)

<ul> 
    <li ng-repeat="(key, value) in jewel"> 
     <span ng-show="!($index==vm.activeIndex)">text here</span> 
     <input ng-show="$index==vm.activeIndex"> 
     <button ng-click="vm.activeIndex = $index"></button> 
    </li> 
</ul> 
0

試試這個:

var app = angular.module('myApp', []); 
 

 
app.controller('MyCtrl',function($scope) { 
 

 
$scope.people = [ 
 
    { 
 
    id: 1, 
 
    name: "Alpha", 
 
    age: "24", 
 
    clicked : false 
 
    }, 
 
{ 
 
    id: 2, 
 
    name: "Beta", 
 
    age: "25", 
 
    clicked : false 
 
    } 
 
]; 
 

 
$scope.showInput = function(person,index) { 
 
person.input = true; 
 
$scope.index = index; 
 
}; 
 

 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="myApp" ng-controller="MyCtrl"> 
 
    <ul> 
 
    <li ng-repeat="person in people"> 
 
     <span ng-show="(!person.input && (index != $index))">text here</span> 
 
     <input ng-show="(person.input && (index == $index))"> 
 
     <button ng-click="showInput(person,$index)">Show Input</button> 
 
    </li> 
 
    </ul>  
 
</div>