0

I'd like to init a filtered list with angularjs, I don't know how to access to ng-init variables...

Edit #1 :

app.controller("AgreementsController", function($scope, $http, $filter) {
    $scope.agreements = [];    
    $http.get('/api/agreement').success(function(data, status, headers, config) {
    $scope.agreements = data.agreements;
    $scope.filteredAgreements = $filter('filter')($scope.agreements,
                                          {number: $scope.search});
});
<tbody ng-init="filteredAgreements = (agreements | filter:{number:search})">
  <tr ng-repeat="agreement in agreements | filter:{number:search} | limitTo:5">
    <td>{{agreement.number}}</td>
  </tr>
</tbody>
{{filteredAgreements.length}} <!-- 291 even if I put "65" into the search -->

6
  • What do you mean by ng-init variables? And where is AgreementsController to be found in the DOM in relation to the HTML you posted? Commented Feb 27, 2015 at 16:37
  • The variables in ng-init... My controller well in the dom but not in the post ;) Commented Feb 27, 2015 at 16:39
  • That's tautology. There are no variables in ngInit. ngInit evaluates an expression in the current scope. If that's the same scope the controller operates on then the controller can access it via the scope. Commented Feb 27, 2015 at 16:46
  • Ok so how to access to filteredAgreements ? Commented Feb 27, 2015 at 17:22
  • Like you did. But agreements is empty when ngInit is run. Therefore filteredAgreements is empty, too. One has to wonder why you use ngInit anyway. Commented Feb 27, 2015 at 17:36

1 Answer 1

1

You get agreements via AJAX, that means at the time the ngInit directive runs they are empty and therefore filteredAgreements will be empty, too. You have to wait until the AJAX call returns.

To use an angular filter in JavaScript you need the $filter service. You call it with the name of the filter to get the filter, and then call that function with the data to be filtered (in your case agreements) and the desired arguments.

app.controller("AgreementsController", function($scope, $http, $filter) {
  $scope.agreements = [];    
  $http.get('/api/agreement').success(function(data, status, headers, config) {
    $scope.agreements = data.agreements;
    $scope.filteredAgreements = $filter('filter')($scope.agreements,
                                              {number: $scope.search});
});

References:

Sign up to request clarification or add additional context in comments.

2 Comments

@tonymx227 And why is it undefined ? I only have the information you give us.
See edit ;) The length of filteredAgreements is 291 even if I put something into the input form...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.