Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
120
rated 0 times [  126] [ 6]  / answers: 1 / hits: 24536  / 10 Years ago, fri, september 5, 2014, 12:00:00

I have this working piece of code that is repeated multiple times, hence would be great for a ng-repeat loop.
For example, two instances of my code are the following.



    <div>
<input type=text ng-model=searchParamaters.userName placeholder=User Name/>
<i class=fa fa-times ng-click=resetSearchField(filterParamDisplay[0].param) ng-show=showParam(filterParamDisplay[0].param)></i>
</div>
<div>
<input type=text ng-model=searchParamaters.userEmail placeholder=User Email/>
<i class=fa fa-times ng-click=resetSearchField(filterParamDisplay[1].param) ng-show=showParam(filterParamDisplay[1].param)></i>
</div>


This is the filterParamDisplay array in Javascript:



    $scope.filterParamDisplay = [
{param: 'userName', displayName: 'User Name'},
{param: 'userEmail', displayName: 'User Email'}
];


I have been trying to do that into a ng-repeat loop, but without success so far.
This is what I have coded atm.



    <div ng-repeat=param in filterParamDisplay>
<input type=text ng-model=searchParams[{{param}}] placeholder={{param.displayName}}/>
<i class=fa fa-times ng-click=resetSearchField(filterParamDisplay[$index].param) ng-show=showParam(filterParamDisplay[$index].param)></i>
</div>


The problems are into the ng-model variable above, and into the $index in the ng-click and ng-show.
Not sure if this can be done at all, any help is much appreciated, thanks!






UPDATE:
Thanks for all the answers, using



     <div ng-repeat=p in filterParamDisplay>
...
ng-model=searchParams[p]


Works great!



Still struggling on the showParam and resetSearchField functions which do not work properly yet using $index. Here is my code.



    $scope.searchParams = $state.current.data.defaultSearchParams;

$scope.resetSearchField = function (searchParam) {
$scope.searchParams[searchParam] = '';
};

$scope.showParam = function (param) {
return angular.isDefined($scope.searchParams[param]);
};

More From » angularjs

 Answers
11

As you bind your ng-models to searchParameters.userName and searchParameters.userMail at first example, you must use searchParameters[param.param] for ng-model in ng-repeat. Also like others said, you don't need to use $index, you got your object as param in ng-repeat scope.



<div ng-repeat=param in filterParamDisplay>
<input type=text ng-model=searchParameters[param.param] placeholder={{param.displayName}}/>
<i class=fa fa-times ng-click=resetSearchField(param.param) ng-show=showParam(param.param)></i>
</div>


Here is working FIDDLE


[#69563] Tuesday, September 2, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
amberlykaliac

Total Points: 415
Total Questions: 100
Total Answers: 85

Location: Wallis and Futuna
Member since Tue, Mar 30, 2021
3 Years ago
;