简体   繁体   中英

toggle in ng-repeat-start and ng-repeat-end in AngularJS

I have two objects.

$scope.OBJ1=[
    {"primaryKey":1,"value":"something1"},
    {"primaryKey":2,"value":"something2"},
    {"primaryKey":3,"value":"something3"},
    {"primaryKey":4,"value":"something4"}
];

$scope.OBJ2=[
    {"primaryKey":1,"dayPart":"dinner"},
    {"primaryKey":1,"dayPart":"lunch"}
];

I am using ng-repeat-start and ng-repeat-end like below :

<tr ng-repeat-start="obj1 in OBJ!" >
    <td colspan="9" >
       {{obj1.value}}
    </td>
</tr>
<tr ng-repeat-end ng-repeat="obj2 in OBJ2" >
    <td>{{obj2.dayPart}}</td>
</tr>

and it producess output :

<tr>something1</tr>
<tr>dinner</tr>
<tr>lunch</tr>

<tr>something2</tr>
<tr>dinner</tr>
<tr>lunch</tr>

<tr>something3</tr>
<tr>dinner</tr>
<tr>lunch</tr>

<tr>something4</tr>
<tr>dinner</tr>
<tr>lunch</tr>

I need to know that how it is possible that when i click on the first tr (for example something1), it toggle the other to tr(dinner and lunch). how can it is achive dynamically. Thanks!!!

I've re-written the above using a directive. You will probably want to give it some polish, but it gives you the idea. I've also changed the table rows and cells to divs and this is better practice, but again, you can change it to fit your requirements.

So the html would look like this:

<objects object-list = 'OBJ1' object-list-two='OBJ2'></objects>

the directive would be as follows:

 myApp.directive('objects', function() {
return {
    restrict: 'E',
    replace: true,
    scope: {
        objectList : '=',
        objectListTwo : '='
    },
    controller: function($scope) {
         $scope.itemSelected ="";

        $scope.showSelected = function(index) {
            console.log("selected index = " + index);
            $scope.itemSelected = $scope.objectList[index];
        };

        $scope.showClass = function(index) {
            return ($scope.itemSelected === $scope.objectList[index] ? "showToggle" : "hideToggle");
        }
    },
    template:      '<div><div ng-repeat-start="obj1 in objectList" >'+
        '    <div colspan="9" ng-click="showSelected($index)" > '+
        '        {{obj1.value}}  '+
        '     </div>   '+
        '        <div ng-repeat="obj2 in objectListTwo" ng-class="showClass($parent.$index)"  >     '+
        '           <div>{{obj2.dayPart}}</div>  '+
        '       </div>  '+
        '     </div>  '+
        '     <div  ng-repeat-end ></div></div>'

};
});

there are a couple of css classes:

 .hideToggle{
    display:none;
 }

.showToggle{
    display:block;
}

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