简体   繁体   中英

Hide elements in ng-repeat

I have an array of such format:

var arr = [{ source: "Hello", target: "Bonjour" },
           { source: "Good morning" },
           { source: "Bye" },
           { source: "Good night" }];

I represent it in the html in the followin way:

<input type="text" ng-model="searchSource">

<div ng-repeat="element in arr | filter: {source: searchSource} track by $index>
    <strong>{{element.source}}</strong>
    <br>
    <input type="text" ng-model="element.target">
    <br>
</div>

I need to make a button, which will hide elements with target property. I made it with the help of filter first, then tried with ng-hide. It works, it hides elements with target but when I start to write something into another <input> fileds they are hidden instantly, and I don't need this behavior.

I need to hide elements only on button press and not while inputting the text. Behavior should be the following:
1) Pressed button, to hide elements with target . It hides first element of arr because it has target . So now there are 3 elements on the screen.
2) Input some text into second element and it shouldn't be hidden.
3) Press the button and all elements are shown.
4) Press the button again and now 1st and 2nd elements are hidden, because they have target

To do so, you have hide the element only at one moment. Not an hide as watchers. This is how I did it. One button hide which will check all your element and hide the one needed. One we will open all your element. While you don't click on hide button again, your item won't be hide.

<input type="text" ng-model="searchSource">
          <button ng-click="hideElement()">Hide</button>
          <button ng-click="isHide = false;">Open</button>
    <div ng-repeat="element in arr | filter: {source: searchSource} track by $index">
        <div ng-hide="element.isHide && isHide">
            <strong>{{element.source}}</strong>
            <br>
            <input type="text" ng-model="element.target"> 
            <br>
        </div>
    </div>

And then you will have a var to hide or not all element. Plus the function which is suppose to hide some specific element.

$scope.isHide = false;

$scope.hideElement = function(){
  $scope.isHide = true;
  for(i = 0; i <$scope.arr.length ; i++){
    if($scope.arr[i].target){
        $scope.arr[i].isHide = true;  
    }
}

This function is manually run so it won't be launch when you will change the value of your element.target

Working Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM